leetcode-Construct Binary Tree from Inorder and Postorder Traversal

605人阅读 评论(0)

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 binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
if (inorder.empty())
return NULL;
return buildTree(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
}
private:
TreeNode *buildTree(vector<int> &inorder, int istart, int iend,
vector<int> &postorder, int pstart, int pend) {
if (istart == iend)
return new TreeNode(inorder[istart]);

int i;
for (i=istart; i<=iend; ++i) {
if (inorder[i]==postorder[pend]) {
break;
}
}

TreeNode *root = new TreeNode(inorder[i]);

if (i>istart)
root->left = buildTree(inorder, istart, i-1, postorder, pstart, pstart+i-istart-1);

if (i<iend)
root->right = buildTree(inorder, i+1, iend, postorder, pstart+i-istart, pend-1);

return root;
}

};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：69707次
• 积分：1262
• 等级：
• 排名：千里之外
• 原创：56篇
• 转载：1篇
• 译文：0篇
• 评论：44条
评论排行
最新评论