Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal

Description: Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

Link: 105. Construct Binary Tree from Preorder and Inorder Traversal

Examples:

Example 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

Example 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]

思路: 给定二叉树,前中后序遍历,只要递归就可以了,但是怎么从前中序遍历中回复二叉树,就想不出,所以看看题解

前序遍历的第一个元素是根节点,在中序遍历的list中找到根节点,以此找到根节点的左右子树,以左右子树的长度,切割先序遍历list的左右子树. 递归函数传入preorder, inorder list, 返回根节点,所以将左右子树的preorder, inorder传入,返回左右子树的根节点,递归建树。

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

同样的方法做 106. Construct Binary Tree from Inorder and Postorder Traversal,后序和中序,建二叉树,根节点是后序的最后一个元素。

class Solution(object):
    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        if not inorder or not postorder:
            return None
        root = TreeNode(postorder[-1])
        i = inorder.index(postorder[-1])
        root.left = self.buildTree(inorder[:i], postorder[:i])
        root.right = self.buildTree(inorder[i+1:], postorder[i:-1])
        return root

但是上面的方法时间和空间的消耗都很大,和使用递归有关系。

还是复习一下关于二叉树的遍历吧,深度优先遍历中有先序,中序和后序,广度优先遍历就是按层遍历,比如计算二叉树深度的时候可以用。其中根节点D,左右子树LR, 先中后表示根节点的位置,而左右子树总是LR. 先左后右。递归遍历的时候,print(root.val); traverse(L), traverse(R)安排序列就可。理解了遍历,才可能完全理解怎么逆方向回去。那么给定先后序,能否还原二叉树呢?答案是不能,先和后的功能是一样的,找到root.val,有了中序才能切分左右子树。

日期: 2021-03-14 每天都在学习,每天也都不在学习。

原文地址:https://www.cnblogs.com/wangyuxia/p/14532348.html