bonfy / algorithm-in-5-minutes

Algorithm in 5 minutes
0 stars 0 forks source link

9. Construct Binary Tree from Preorder and Inorder Traversal #9

Open bonfy opened 5 years ago

bonfy commented 5 years ago

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

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

Leetcode: 105. Construct Binary Tree from Preorder and Inorder Traversal - https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

bonfy commented 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完

image