leetcode刷题笔记一百零六题 从中序与后序遍历序列构造二叉树

leetcode刷题笔记一百零六题 从中序与后序遍历序列构造二叉树

源地址:106. 从中序与后序遍历序列构造二叉树

问题描述:

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

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

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

3

/
9 20
/
15 7

/**
与105题解法类似,只不过根节点通过后序遍历的尾结点判断
*/
/**
 * Definition for a binary tree node.
 * class TreeNode(var _value: Int) {
 *   var value: Int = _value
 *   var left: TreeNode = null
 *   var right: TreeNode = null
 * }
 */
object Solution {
    def buildTree(inorder: Array[Int], postorder: Array[Int]): TreeNode = {
        val inorderLen = inorder.length
        val postorderLen = postorder.length
        if (inorderLen != postorderLen) return null
        def helper(inorder: Array[Int], postorder: Array[Int], inLeft: Int, inRight: Int, postLeft: Int, postRight: Int): TreeNode = {
            //递归终止条件
            if (inLeft > inRight || postLeft > postRight) return null
            val povit = postorder(postRight)
            val root = new TreeNode(povit)
            val povitIndex = inorder.indexOf(povit)
            root.left = helper(inorder, postorder, inLeft, povitIndex-1, postLeft, postRight - (inRight - povitIndex)-1)
            root.right = helper(inorder, postorder, povitIndex+1, inRight, postLeft+povitIndex-inLeft, postRight-1)
            return root
        }
        return helper(inorder, postorder, 0, inorderLen-1, 0, postorderLen-1)
    }
}
原文地址:https://www.cnblogs.com/ganshuoos/p/13434656.html