[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal -Python

原题:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/

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

基础知识:

给定一个二叉树的先序遍历中序遍历,构造出一颗二叉树。

二叉树的遍历分为先序遍历、中序遍历、后序遍历、层序遍历。

而通过先序遍历和中序遍历、中序遍历和后序遍历 是可以还原该二叉树结构的。

例如:

以如下二叉树为例。 
其先序遍历结果是:【4 2 1 3 7 6 9】 
中序遍历结果是:【1 2 3 4 6 7 9】

对先序遍历来说:

先序遍历的每个值表示的结点都是接下来的若干结点的父结点。

比如【4】是这个二叉树的根结点。 
【2】是【1 3】的父结点。 
【1】是 空的父结点,也即使叶子结点。

对中序遍历来说:

根结点一定在中间位置,中间左边是左子树,右边是右子树。 
比如【4】左边是【1 2 3】是根结点的左子树,右边是【6 7 9】是根结点的右子树。 
对于【2】来说,【1】是其左子树,【3】是其右子树。 
…… 
依次类推。

很明显,这是一个递归过程。

代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if len(preorder) == 0:return None
        root_node = TreeNode(preorder[0])
        j = inorder.index(preorder[0])
        root_node.left  = self.buildTree(preorder[1:j+1],inorder[0:j])
        root_node.right = self.buildTree(preorder[j+1:],inorder[j+1:])
        return root_node
        

猜你喜欢

转载自blog.csdn.net/jiangjiang_jian/article/details/81263058