根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
这个题想通了就不难了,前序遍历的第一个一定是根节点,然后在中序遍历中找到这个节点,这个节点左右又是本节点左右的中序遍历,前序遍历中左子树的数目和中序一定一样,所以前序遍历从第二个点开始的到最后划分为前后两个集合(根据中序遍历得到的左右子树数目),这就是左右子树的前序遍历集合。以此递归即可。
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) {
return buildTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
TreeNode* buildTree(vector<int>& preorder, int pLeft, int pRight, vector<int>& inorder, int iLeft, int iRight){
if (pLeft > pRight || iLeft > iRight) return NULL;
int i = 0;
for(i=iLeft;i<=iRight;i++){
if(preorder[pLeft]==inorder[i]) break;
}
TreeNode* cur = new TreeNode(preorder[pLeft]);
cur->left = buildTree(preorder, pLeft + 1, pLeft+i-iLeft, inorder, iLeft, i-1);
cur->right = buildTree(preorder, pLeft+i-iLeft+1, pRight, inorder, i+1, iRight);
return cur;
}
};
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:
return self.buildTree2(preorder, 0, len(preorder)-1, inorder, 0, len(inorder)-1)
def buildTree2(self, preorder, pLeft, pRight, inorder, iLeft, iRight):
if pLeft > pRight or iLeft > iRight:
return None
i = 0
for i in range(iRight+1):
if preorder[pLeft]==inorder[i]:
break;
cur = TreeNode(preorder[pLeft])
cur.left = self.buildTree2(preorder, pLeft+1, pLeft+i-iLeft, inorder, iLeft, i-1)
cur.right = self.buildTree2(preorder, pLeft+i-iLeft+1, pRight, inorder, i+1, iRight)
return cur