106.从中序与后序遍历序列构造二叉树

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

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

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

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

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

题目分析

此题与105题完全类似,就不赘述了,分析可以看105题,这边就直接给出代码吧。

代码

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

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

猜你喜欢

热点阅读