zoukankan      html  css  js  c++  java
  • 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)
        }
    }
    
  • 相关阅读:
    洛谷P2466 [SDOI2008]Sue的小球 题解 区间DP+费用提前计算
    中国国家集训队论文集目录(1999-2008)
    洛谷P1726 上白泽慧音 题解 强连通分量
    洛谷P1410 子序列 题解 动态规划
    树堆(Treap)学习笔记 2020.8.12
    伸展树(Splay)学习笔记
    git操作
    yii 缓存探究
    yii之srbac详解
    一个PDO类
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13434597.html
Copyright © 2011-2022 走看看