构造二叉树
构造二叉树
105. 从前序与中序遍历序列构造二叉树
例:
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
二叉树:
3
/ \
9 20
/ \
15 7
/**
* 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:
vector<int> pre, in;
map<int, int> pos;
TreeNode* build(int pre_l, int pre_r, int in_l, int in_r){
if(pre_l > pre_r) return nullptr;
int pre_val = pre[pre_l];
int p = pos[pre_val];
int num = p-in_l;
TreeNode* root = new TreeNode(pre_val);
root-> left = build(pre_l+1, pre_l+num, in_l, p-1);
root -> right = build(pre_l+num+1, pre_r, p+1, in_r);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
pre = preorder; in = inorder;
for(int i = 0; i < inorder.size(); i++) pos[inorder[i]] = i;
return build(0, preorder.size()-1, 0, inorder.size()-1);
}
};
106. 从中序与后序遍历序列构造二叉树
例:
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
二叉树:
3
/ \
9 20
/ \
15 7
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> in, post;
map<int, int> pos;
int rt;
TreeNode* build(int l, int r){
if(l > r) return nullptr;
int post_val = post[rt];
int p = pos[post_val];
TreeNode* root = new TreeNode(post_val);
rt--;
root -> right = build(p+1, r);
root-> left = build(l, p-1);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
in = inorder; post = postorder;
rt = inorder.size()-1;
for(int i = 0; i < inorder.size(); i++) pos[inorder[i]] = i;
return build(0, rt);
}
};
889. 根据前序和后序遍历构造二叉树
返回与给定的前序和后序遍历匹配的任何二叉树
。
例:
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
二叉树:
1
/ \
2 3
/ \ / \
4 5 6 7
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode constructFromPrePost(int[] pre, int[] post) {
int N = pre.length;
if (N == 0) return null;
TreeNode root = new TreeNode(pre[0]);
if (N == 1) return root;
int L = 0;
for (int i = 0; i < N; ++i)
if (post[i] == pre[1])
L = i+1;
root.left = constructFromPrePost(Arrays.copyOfRange(pre, 1, L+1),
Arrays.copyOfRange(post, 0, L));
root.right = constructFromPrePost(Arrays.copyOfRange(pre, L+1, N),
Arrays.copyOfRange(post, L, N-1));
return root;
}
}