输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出:
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3 / \ 9 20 / \ 15 7
代码:
- 递归遍历
# 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:
#递归结束条件
if len(preorder) == 0:
return None
x, i = preorder[0], 0
while inorder[i] != x:
i += 1
left_tree = self.buildTree(preorder[1:i+1], inorder[0:i])
right_tree = self.buildTree(preorder[i+1:], inorder[i+1:])
root = TreeNode()
root.val = preorder[0]
root.left = left_tree
root.right = right_tree
return root
2.也是递归:
# 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:
if len(preorder) == 0:
return None
root_val = preorder[0]
idx = inorder.index(root_val)
root = TreeNode(root_val)
left_tree = self.buildTree(preorder[1:idx+1], inorder[:idx])
right_tree = self.buildTree(preorder[idx+1:], inorder[idx+1:])
root.left = left_tree
root.right = right_tree
return root
3.上面的方法在inoder.index的时候每次都会迭代一个inoder,导致时间复杂度增加,可以使用哈希查找的思路。可以先创建一个字典,来存储inorder值和index的关系。