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)
        }
    }
    
  • 相关阅读:
    Vue3源码系列之触发更新的实现
    Vue3源码系列之依赖收集的实现
    Vue3源码系列之reactiveApi实现
    删除链表的倒数第n个节点
    Shared_ptr 参考实现
    linux 目录结构 比较老
    C++11 bind function
    状态机DP
    尾递归
    秒杀系统的构建(2)
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13434597.html
Copyright © 2011-2022 走看看