zoukankan      html  css  js  c++  java
  • [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal(根据二叉树的前序和中序遍历构建二叉树)

    Description

    Given preorder and inorder traversal of a tree, construct the binary tree.Given preorder and inorder traversal of a tree, construct the binary tree.

    Note:
    You may assume that duplicates do not exist in the tree.

    For example, given

    preorder = [3,9,20,15,7]
    inorder = [9,3,15,20,7]

    Return the following binary tree:

        3
       / 
      9  20
        /  
       15   7
    

    Solution

    给定二叉树的前序和中序遍历,构建这棵二叉树。这题其实不难,前序遍历的第一个就是 root,然后用这个 root 去中序遍历里确立左右子树的范围。但是代码依旧写不出来,因为感觉写一个至少六个入参的递归函数总觉得哪里都会出错。后面看了 discussion 后恍然大悟,没有必要死死卡在原数组上,直接根据之前的信息生成左右子数组,进行递归调用即可,代码如下:

    class Solution {
        fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
            if (preorder.isEmpty() || inorder.isEmpty()) {
                return null
            }
            if (preorder.size == 1) {
                return TreeNode(preorder[0])
            }
            val result = TreeNode(preorder[0])
            val rootIndex = inorder.indexOf(preorder[0])
            result.left = buildTree(
                preorder.sliceArray(1..rootIndex),
                inorder.sliceArray(0 until rootIndex)
            )
            result.right = buildTree(
                preorder.sliceArray(rootIndex + 1..preorder.lastIndex),
                inorder.sliceArray(rootIndex + 1..inorder.lastIndex)
            )
            return result
        }
    }
    
  • 相关阅读:
    hadoopnamenode配置及问题处理方案
    hadoop 运行 Java程序
    hadoop命令大全
    DOS
    腾讯Linux QQ安装
    linux下安装realplayer
    在linux中配置安装telnet服务
    关于C#静态构造函数的几点说明
    linux下的Network File Server共享配置
    Oracle学习笔记
  • 原文地址:https://www.cnblogs.com/zhongju/p/13976743.html
Copyright © 2011-2022 走看看