按照前序遍历和中序遍历构建二叉树
生活随笔
收集整理的這篇文章主要介紹了
按照前序遍历和中序遍历构建二叉树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉載自:http://blog.csdn.net/sbitswc/article/details/26433051
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
There is an example. _______7______/ \__10__ ___2/ \ /4 3 _8\ /1 11 The preorder and inorder traversals for the binary tree above is: preorder = {7,10,4,3,1,2,8,11} inorder = {4,10,3,1,7,11,8,2}
The first node in preorder alwasy the root of the tree. We can break the tree like:
1st round:
preorder: ?{7}, {10,4,3,1}, {2,8,11}
inorder: ? ? {4,10,3,1}, {7}, {11, 8,2}
_______7______/ \{4,10,3,1} {11,8,2} Since we alreay find that {7} will be the root, and in "inorder" sert, all the data in the left of {7} will construct the left sub-tree. And the right part will construct a right sub-tree. We can the left and right part agin based on the preorder. 2nd round
left part ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?right part
preorder: {10}, {4}, {3,1} ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{2}, {8,11}
inorder: ?{4}, {10}, {3,1} ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{11,8}, {2}
_______7______/ \__10__ ___2/ \ /4 {3,1} {11,8} see that, {10} will be the root of left-sub-tree and {2} will be the root of right-sub-tree.
Same way to split {3,1} and {11,8}, yo will get the complete tree now.
_______7______/ \__10__ ___2/ \ /4 3 _8\ /1 11 So, simulate this process from bottom to top with recursion as following code. c++
[cpp] view plain copy
java
[java] view plain copy
總結
以上是生活随笔為你收集整理的按照前序遍历和中序遍历构建二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 晚上喝豆浆可以减肥吗
- 下一篇: OpenCV Stitching_det