(二叉树存储+递归遍历)Binary Tree Traversals
題目:
A binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
Input
The input contains several test cases. The first line of each test case contains a single integer n (1<=n<=1000), the number of vertices of the binary tree. Followed by two lines, respectively indicating the preorder sequence and inorder sequence. You can assume they are always correspond to a exclusive binary tree.
Output
For each test case print a single line specifying the corresponding postorder sequence.
Sample Input
9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6
Sample Output
7 4 2 8 9 5 6 3 1
分析與解答:
1.二叉樹有根結(jié)點(diǎn),有兩個(gè)子結(jié)點(diǎn),而且子結(jié)點(diǎn)數(shù)據(jù)類型和根節(jié)點(diǎn)相同,因此我們用struct存儲(chǔ)
2.根據(jù)題中給的數(shù)據(jù)建樹,先序后序中序,知道任意兩個(gè)就可以建樹
這題是給了中序和先序,左根右,根左右
主要問(wèn)題就是根據(jù)遍歷的性質(zhì)找根,然后遞歸建立左子樹右子樹
先序:1 2 4 7 3 5 8 9 6
中序:4 7 2 1 8 5 9 3 6
先序第一個(gè)1是根
所以從中序開始找,472應(yīng)當(dāng)是第一個(gè)根的左子樹
對(duì)應(yīng)先序的247,可知,如果把左子樹從新看成二叉樹,那他的根就是2
再繼續(xù)找,把左子樹找完了
右子樹35896 根是3,然后繼續(xù)找
總結(jié)一下思想:
先創(chuàng)一個(gè)結(jié)點(diǎn),他的根直接知道就是先序第一個(gè)數(shù),先認(rèn)為他沒(méi)有左右子結(jié)點(diǎn)(因?yàn)槿绻f歸到最后一個(gè)子葉,他沒(méi)有子結(jié)點(diǎn))
找到根后,通過(guò)遞歸調(diào)用,填他的左子樹的結(jié)點(diǎn)值右子樹的結(jié)點(diǎn)值
輸出的話如果后序,輸出:左子樹,右子樹,根
這題是由于空格的原因,我把數(shù)存到數(shù)組里了
總結(jié)
以上是生活随笔為你收集整理的(二叉树存储+递归遍历)Binary Tree Traversals的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: (递归1)爬楼梯
- 下一篇: jmeter进程和线程的区别_一文搞懂进