您的位置:首页 > 其它

[Leetcode] #105 Construct Binary Tree from Preorder and Inorder Traversal

2017-02-11 19:49 561 查看

Discription:

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

Note:

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

Solution:

TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder, int ps, int pe, int is, int ie)
{
if (ps > pe) return NULL;
TreeNode *root = new TreeNode(preorder[ps]);
int x;
for (int i = is; i <= ie; i++){
if (inorder[i] == root->val){
x = i;
break;
}
}
root->left = buildTree(preorder, inorder, ps + 1, ps + x - is, is, x - 1);
root->right = buildTree(preorder, inorder, pe - ie + x + 1, pe, x + 1, ie);
return root;
}

TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return buildTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
}

GitHub-LeetCode: https://github.com/wenwu313/LeetCode

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐