Open bonfy opened 5 years ago
解法: 递归
# 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 inorder:
idx = inorder.index(preorder.pop(0))
root = TreeNode(inorder[idx])
root.left = self.buildTree(preorder, inorder[0:idx])
root.right = self.buildTree(preorder, inorder[idx+1:])
return root
说明: 巧妙在 pop(0) 在 然后 root.left = self.buildTree(preorder, inorder[0:idx])
递归会先把左边的全部pop完
Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
For example, given
Return the following binary tree:
Leetcode: 105. Construct Binary Tree from Preorder and Inorder Traversal - https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/