105.从前序与中序遍历序列构造二叉树

2020-01-21  本文已影响0人  qiHuang112

题目#105.从前序与中序遍历序列构造二叉树

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

题目分析

题中提到,给出两个数组分别保存二叉树的前序遍历和中序遍历,如何从前序遍历和中序遍历恢复二叉树呢?
我们可以拿题中给出的二叉树分析分析:
对于下面两个数组以及二叉树的前中序遍历的定义:

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
    3
   / \
  9  20
    /  \
   15   7

我们可以分别将前中序遍历的两个数组分为三个部分,分别为根节点与左右子树:

前序遍历 preorder = [3] [9] [20,15,7]
中序遍历 inorder = [9] [3] [15,20,7]

下面说下为什么这么分:

构建二叉树

上面的分析帮我们将数组分为了左右子树和根节点,我们得到了左右子树和新的左右子树区间,递归就呼之欲出了。

递归已经使我们的老熟人了,同样还是考虑两点:

最终代码

class Solution {
    fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
        return buildTree(preorder, 0, preorder.lastIndex, inorder, 0, inorder.lastIndex)
    }

    private fun buildTree(preorder: IntArray, a: Int, b: Int, inorder: IntArray, c: Int, d: Int): TreeNode? {
        if (a > b) return null
        val root = TreeNode(preorder[a])
        val index = inorder.indexOf(preorder[a])
        val countLeft = index - c
        val countRight = d - index
        root.left = buildTree(preorder, a + 1, a + countLeft, inorder, c, c + countLeft - 1)
        root.right = buildTree(preorder, b - countRight + 1, b, inorder, d - countRight + 1, d)
        return root
    }
}
上一篇 下一篇

猜你喜欢

热点阅读