首页 > 代码库 > Construct Binary Tree from Inorder and Postorder Traversal

Construct Binary Tree from Inorder and Postorder Traversal

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 };