- 07 重建二叉树
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
限制: 0 <= 节点个数 <= 5000
解题思路:【c++】遍历前序遍历所有元素,根节点前序下标为pre_index,新建根节点preorder[pre_index],遍历中序遍历找到等于该值的节点,下标in_cur,该节点左侧所有节点构成左子树,个数为k,右侧构成右子树。新建的根节点的左子节点前序下标为pre_index+1,右子节点为pre_index+1+k,以这两个子节点作为根节点再分割其左右子树,重复上述步骤。
//c++
/**
* 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:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
if (n <= 0)
return NULL;
return buildTreeBranch(preorder, inorder, 0, n-1, 0, n-1);
}
TreeNode* buildTreeBranch(vector<int> preorder, vector<int> inorder, int pre_index, int pre_right, int in_left, int in_right) {
if(pre_index > pre_right || in_left > in_right) return NULL;
TreeNode* node = new TreeNode(preorder[pre_index]);
int k =0;
int in_cur = in_left;
while(preorder[pre_index] != inorder[in_cur]){
k++;
in_cur++;
}
node->left = buildTreeBranch(preorder, inorder, pre_index+1, pre_index+k, in_left, in_cur-1);
node -> right = buildTreeBranch(preorder, inorder,pre_index+k+1, pre_right, in_cur+1, in_right );
return node;
}
};
Notes:
注意左右子树的前序搜索边界,左子树:pre_index+1----pre_index+k,右子树:pre_index+k+1------pre_right;中序搜索边界,左子树:in_left—in_cur-1,右子树:in_cur+1----in_right。
#python3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
n = len(preorder)
if n == 0:
return None
return self.buildTreeBranch(preorder, inorder, 0, n-1, 0, n-1) #需要加self.
def buildTreeBranch(self, preorder: List[int], inorder: List[int], pre_index: int, pre_right:int, in_left: int, in_right: int) -> TreeNode:
if pre_index> pre_right or in_left > in_right:
return None
node = TreeNode(preorder[pre_index])
k = 0
in_curr = in_left
while(preorder[pre_index] != inorder[in_curr]):
k= k+1;
in_curr= in_curr+1;
node.left = self.buildTreeBranch(preorder, inorder, pre_index+1, pre_index + k, in_left, in_curr-1)
node.right = self.buildTreeBranch(preorder, inorder, pre_index+k+1, pre_right, in_curr+1, in_right)
return node