自己开发的博客网站,欢迎访问 www.weiboke.online
#889. Construct Binary Tree from Preorder and Postorder Traversal
Return any binary tree that matches the given preorder and postorder traversals.
Values in the traversals pre and post are distinct positive integers.
Example 1:
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
Note:
- 1 <= pre.length == post.length <= 30
- pre[] and post[] are both permutations of 1, 2, …, pre.length.
- It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.
##Approach
- 很好的一道题,题目大意是给你前序序列和后序序列构造树,返回任一结果即可,写习惯了前序或后序加中序构造树,突然还是有点懵的,不过原理都是一样,我们还是要确定左右子树的区间,前序序列的第二数就是左子树的头,所以可以后序序列确定左子树可能的长度为多少,那么我们就可以构造了。
- 第一种写法我是参照题解,第二种就是以前常写的,均可AC。
Code
class Solution {
public:
TreeNode* CreateTree(vector<int>& pre, vector<int>& post, int pref, int postf, int N) {
if (N == 0)return nullptr;
TreeNode*root = new TreeNode(pre[pref]);
if (N == 1)return root;
int L = 1;
for (; L < N; L++) {
if (pre[pref + 1] == post[postf + L - 1])break;
}
root->left = CreateTree(pre, post, pref + 1, postf, L);
root->right = CreateTree(pre, post, pref + L + 1, postf + L, N - L - 1);
return root;
}
TreeNode* CreateTree(vector<int>& pre, vector<int>& post,int preL,int preR,int postL,int postR) {
if (preL > preR)return nullptr;
TreeNode*root = new TreeNode(pre[preL]);
if (preL == preR)return root;
int j = postL;
for (; j < postR; j++) {
if (post[j] == pre[preL + 1])break;
}
int leftNumber = j - postL + 1;
root->left = CreateTree(pre, post, preL + 1, preL + leftNumber, postL, postL + leftNumber - 1);
root->right = CreateTree(pre, post, preL + leftNumber + 1, preR, postL + leftNumber, postR-1);
return root;
}
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
return CreateTree(pre, post, 0, pre.size() - 1, 0, post.size());
}
};
本文介绍了一种使用前序和后序遍历构建二叉树的方法,通过实例展示了如何确定左右子树的区间,并提供了两种实现方式的代码示例。


被折叠的 条评论
为什么被折叠?



