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

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

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

问题描述:

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

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

例如,给出

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

3

/
9 20
/
15 7

/**
本题是从中序与前序构成树的结构问题,这类问题关键在于寻找根节点,在中序遍历中利用根节点,分为左子树与右子树区间处理
*/
/**
 * 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(preorder: Array[Int], inorder: Array[Int]): TreeNode = {
        def helper(preorder: Array[Int], inorder: Array[Int], preLeft: Int, preRight: Int, inLeft: Int, inRight: Int): TreeNode = {
            //递归终止条件
            if (preLeft > preRight || inLeft > inRight) return null
            //根节点
            val pivot = preorder(preLeft)
            val root = new TreeNode(pivot)
            val pivotIndex = inorder.indexOf(pivot)
            root.left = helper(preorder, inorder, preLeft+1, preLeft+pivotIndex-inLeft, inLeft, pivotIndex-1)
            root.right = helper(preorder, inorder, preLeft+1+pivotIndex-inLeft, preRight, pivotIndex+1, inRight)
            return root
        }
        if (preorder.length != inorder.length) return null
        return helper(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1)
    }
}
原文地址:https://www.cnblogs.com/ganshuoos/p/13434597.html