注意new node 必須寫 申請位址空間
node * root = new node()
;//可以
struct node* root;
//不行
//給定一棵二叉樹的後序遍歷和中序遍歷,請你輸出其層序遍歷的序列。
//這裡假設鍵值都是互不相等的正整數。
#include
#include
#include
#include
using namespace std;
vector<
int> v;
int post[50]
,in[50]
;struct node
;node*
createtree
(int postl,
int postr,
int inl,
int inr)
}int leftnum=index-inl;
//3//2 3 1 5 7 6 |4(root)|
//1 2 3 |4(root)| 5 6 7-----------------------------
//2 3 1|| 5 7 6 |4(root)|----------------------------
//1(root) 2 3 |4(root)| 5 6(root) 7
root->lchild=
createtree
(postl,postl+leftnum-
1,inl,index-1)
;//postl,postl+leftnum-1,inl,index-1
root->rchild=
createtree
(postl+leftnum,postr-
1,index+
1,inr)
;//postl+leftnum,postr-1,index+1,inr
return root;
}void
bfs(node* node)
}int
main()
for(
int i=
0;i) node* root=
createtree(0
,n-1,0
,n-1);
//後序,中序
bfs(root)
;for
(int i=
0;isize()
;i++
)return0;
}
樹的遍歷 已知中序 前序 後序)求層次遍歷
先來看一道題目 時間限制 400 ms 記憶體限制 65536 kb 長度限制 8000 b 判題程式 standard 作者 陳越 給定一棵二叉樹的後序遍歷和中序遍歷,請你輸出其層序遍歷的序列。這裡假設鍵值都是互不相等的正整數。輸入格式 輸入第一行給出乙個正整數n 30 是二叉樹中結點的個數。第二...
資料結構 樹的遍歷(先序,中序,後序,層次)
通過先序方式建立樹,通過簡單的遞迴就可以實現先序,中序,後序遍歷。層次遍歷還需要用到佇列,當某個節點出隊時,它的左右結點要入隊 如果有的話 include include using namespace std typedef struct node node 通過先序方式建立樹,表示空 a b c...
二叉樹先序遍歷,中序遍歷,後序遍歷,層次遍歷。
原理 如圖 先序遍歷結果為 abdhecfg 首先從根節點開始,然後左節點,左節點成為根節點,然後再左節點,然後右節點 如果左子樹遍歷完後就遍歷該根節點的右子樹 中序遍歷結果為 hdbeafcg 當左節點被讀取後,左節點被當作根節點 後序遍歷結果為 hdebfgca 注意每個節點的左右子樹必須遍歷完...