您的位置:首页 > 其它

LeetCode:Construct Binary Tree from Inorder and Postorder Traversal,Construct Binary Tree from Preorder and Inorder Traversal

2013-11-24 21:48 399 查看
LeetCode: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. 本文地址

分析:后序序列的最后一个元素就是树根,然后在中序序列中找到这个元素(由于题目保证没有相同的元素,因此可以唯一找到),中序序列中这个元素的左边就是左子树的中序,右边就是右子树的中序,然后根据刚才中序序列中左右子树的元素个数可以在后序序列中找到左右子树的后序序列,然后递归的求解即可

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
typedef vector<int>::iterator Iter;
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
return buildTreeRecur(inorder.begin(), inorder.end(), postorder.begin(), postorder.end());
}
TreeNode *buildTreeRecur(Iter istart, Iter iend, Iter pstart, Iter pend)
{
if(istart == iend)return NULL;
int rootval = *(pend-1);
Iter iterroot = find(istart, iend, rootval);
TreeNode *res = new TreeNode(rootval);
res->left = buildTreeRecur(istart, iterroot, pstart, pstart+(iterroot-istart));
res->right = buildTreeRecur(iterroot+1, iend, pstart+(iterroot-istart), pend-1);
       return res;
}
};


LeetCode:Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder 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:
typedef vector<int>::iterator Iter;
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
return buildTreeRecur(inorder.begin(), inorder.end(), preorder.begin(), preorder.end());
}
TreeNode *buildTreeRecur(Iter istart, Iter iend, Iter pstart, Iter pend)
{
if(istart == iend)return NULL;
int rootval = *pstart;
Iter iterroot = find(istart, iend, rootval);
TreeNode *res = new TreeNode(rootval);
res->left = buildTreeRecur(istart, iterroot, pstart+1, pstart+1+(iterroot-istart));
res->right = buildTreeRecur(iterroot+1, iend, pstart+1+(iterroot-istart), pend);
return res;
}
};


【版权声明】转载请注明出处:/article/4879658.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐