leetcode: Construct Binary Tree from Preorder and Inorder Traversal

本文介绍了一种利用递归方法根据前序遍历和中序遍历序列重建二叉树的方法。通过确定根节点,并在中序序列中找到根节点的位置来划分左右子树,进而递归构建整棵树。

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

还是采取递归的思路。   找到找到每棵子树的根节点以及左子结点和右子结点的前序和中序集合.....对其递归调用本函数得到左子树和右子树,从而实现了当前子树的建立.....

由于前序序列首先访问根节点.....因而可以确定根节点.....对于前序和中序来说,始终都是最后才访问右子树.....因而在前序序列和中序序列中,右子树节点的长度和位置都是相同的;同样左子树也是连续分布且长度相同....

在前序序列中,分布为根节点->左子结点集合->右子结点集合

在中序序列中,分布为左子结点集合->根节点->右子结点集合

由于我们已经确定了根节点,因而可以很轻松的在中序序列中找到根节点的位置从而分隔出左子结点和右子结点的集合


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {

        return fun(preorder,inorder);
    }
    TreeNode fun(int[] preorder,int[] inorder)
    {
        if(preorder.length==0)
        {
            return null;
        }
        TreeNode root = new TreeNode(preorder[0]);
        int rootIndex = 0;
        for(;rootIndex<inorder.length;rootIndex++)
        {
            if(inorder[rootIndex]==preorder[0])
            {
                break;
            }
        }
        int[] preLeft = new int[rootIndex];
        for(int i=1;i<=rootIndex;i++ )
        {
            preLeft[i-1] = preorder[i];
        }
        int[] preRight = new int[preorder.length-1-rootIndex];
        for(int i=rootIndex+1;i<preorder.length;i++)
        {
            preRight[i-rootIndex-1] = preorder[i];
        }
        int[] inLeft = new int[rootIndex];
        for(int i=0;i<rootIndex;i++ )
        {
            inLeft[i] = inorder[i];
        }
        int[] inRight = new int[inorder.length-1-rootIndex];
        for(int i=rootIndex+1;i<inorder.length;i++)
        {
            inRight[i-rootIndex-1] = inorder[i];
        }
        root.left = fun(preLeft,inLeft);
        root.right = fun(preRight,inRight);
        return root;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值