当前位置 博文首页 > 文章内容

    [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal(根据二叉树的前序和中序遍历构建二叉树)

    作者: 栏目:未分类 时间:2020-11-15 15:00:01

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    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
        }
    }