有序陣列轉化為二叉樹 C++
阿新 • • 發佈:2019-02-09
http://blog.csdn.net/fanzitao/article/details/8031946
這個題目有點模稜兩可,只說轉化成二叉樹。也沒有說平衡二叉樹,二叉排序樹。
如果只是隨便什麼二叉樹都可以,把就用陣列作為輸出,隨便是前序,中序,還是後續構建二叉樹都可以,網上二叉樹建立的程式碼一大堆。
下面程式碼是簡歷一棵二叉排序樹。
首先用陣列的中間元素作為根建立二叉樹,然後遞迴簡歷左子樹,右子樹。
- #include<iostream>
- #include<queue>
- #include<windows.h>
-
usingnamespace std;
- typedefstruct node{
- int data;
- struct node *left;
- struct node *right;
- }Node,*Bitree;
- void buildTree(Bitree &T,int a[],int begin,int end)//建立二叉排序樹
- {
- if(begin>end)//遞迴的出口
- return;
- int mid = (begin+end)/2;//中間元素的下標
-
if(T==NULL)//為當前樹的根節點申請空間
- {
- T = (Node *)malloc(sizeof(Node));
- T->data = a[mid];//賦值
- T->left = NULL;//左右子樹也要置為NULL
- T->right = NULL;
- }
- cout<<a[mid]<<" ";//下面2行為了方便看建立的過程
- Sleep(1000);
-
buildTree(T->left,a,begin,mid-1);//遞迴簡歷左子樹
- buildTree(T->right,a,mid+1,end);//遞迴建立右子樹
- }
- void travel(Bitree T)
- {
- if(T != NULL)
- {
- travel(T->left);
- cout<<T->data<<" ";//中序遍歷
- travel(T->right);
- }
- }
- int main()
- {
- int a[] = {1,2,3,4,5,6,7,8,9};
- Bitree root = NULL;
- int begin = 0, end = 8;
- buildTree(root,a,begin,end);
- cout<<endl;
- travel(root);
- getchar();
- return 0;
- }