您的位置:首页 > 其它

[Leetcode]Construct Binary Tree from Inorder and Postorder Traversal

2015-10-24 14:44 363 查看
Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

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

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
/*algorithm: divide and conquer
from postorder to get the root,
based on root, separate the inorder list to two list
recrusive this process,
*///[start,end) [1,2,3] [1,3,2]
TreeNode* buildTreeSub(vector<int>&in,vector<int>&post,int is,int ilen,int ps,int plen)
{
if(plen < 1)return NULL;
int v = post[ps + plen - 1];
TreeNode* root = new TreeNode(v);
int i = 0;
for(i = 0;i < ilen && in[i+is] != v;++i);
root->left = buildTreeSub(in,post,is,i,ps,i);
root->right = buildTreeSub(in,post,is+i+1,ilen-(i+1),ps+i,plen-(i+1));
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTreeSub(inorder,postorder,0,inorder.size(),0,postorder.size());
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: