【LeetCode题目记录-2】从前序遍历和中序遍历构建二叉树

本文详细介绍了如何通过先序和中序遍历的数组构建二叉树,包括递归调用和辅助Stack两种方法,旨在帮助开发者理解二叉树构建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Construct Binary Tree from Preorder and Inorder Traversal

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

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

【分析1-非原创】递归调用。

参考:http://bylijinnan.iteye.com/blog/1355279

    public static TreeNode buildTree(int[] preorderint[] inorder) {

        if (preorder == null || inorder == null) {

            return null;

        }

        return build(preorder, 0, preorder.length - 1, inorder, 0,

                inorder.length - 1);

    }

    /*递归建立二叉树,在preorder中获取根节点,在inorder查找根节点,获取一个偏移量offset是左子树的节点个数

     * 注意截止条件

     * */

    public static TreeNode build(int[] preorderint start1int end1,

            int[] inorderint start2int end2) {

        if (start1 > end1 || start2 > end2) {

            return null;

        }

        int rootVal = preorder[start1];

        TreeNode root = new TreeNode(rootVal);

        int divider = getDivider(inorderstart2end2rootVal);

        int offSet = divider - start2;

        TreeNode left = build(preorderstart1 + 1, start1 + offSetinorder,

                start2start2 + offSet - 1);

        TreeNode right = build(preorderstart1 + offSet + 1, end1inorder,

                divider + 1, end2);

        root.left = left;

        root.right = right;

        return root;

 

    }

 

    public static int getDivider(int[] inorderint startint endint arg) {

        for (int i = starti <= endi++) {

            if (inorder[i] == arg) {

                return i;

            }

        }

        return -1;

    }

【分析1-非原创】辅助Stack

参考:https://oj.leetcode.com/discuss/2297/the-iterative-solution-is-easier-than-you-think

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值