码迷,mamicode.com
首页 > 其他好文 > 详细

Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-08-17 16:52:12      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   strong   ar   art   

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

思路:利用后序遍历提供的根节点信息,在中序遍历中找到根节点,从而得到{左子树,根,右子树},递归对求解左右子树即可。

 1 class Solution {
 2 public:
 3     TreeNode *buildTree( vector<int> &inorder, vector<int> &postorder ) {
 4         if( inorder.empty() || inorder.size() != postorder.size() ) { return 0; }
 5         return BuildSub( inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1 );
 6     }
 7 private:
 8     TreeNode *BuildSub( vector<int> &inorder, int inStart, int inEnd, vector<int> &postorder, int postStart, int postEnd ) {
 9         if( inStart > inEnd ) { return 0; }
10         int index = 0;
11         while( postorder[postEnd] != inorder[inStart+index] ) { ++index; }
12         TreeNode *treeNode = new TreeNode( inorder[inStart+index] );
13         treeNode->left = BuildSub( inorder, inStart, inStart+index-1, postorder, postStart, postStart+index-1 );
14         treeNode->right = BuildSub( inorder, inStart+index+1, inEnd, postorder, postStart+index, postEnd-1 );
15         return treeNode;
16     }
17 };

 

Construct Binary Tree from Inorder and Postorder Traversal,布布扣,bubuko.com

Construct Binary Tree from Inorder and Postorder Traversal

标签:style   blog   color   os   io   strong   ar   art   

原文地址:http://www.cnblogs.com/moderate-fish/p/3917798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!