LeetCode(105) Construct Binary Tree from Preorder and Inorder Traversal解题报告

本文详细介绍了如何通过给定的先序和中序遍历序列来构建二叉树,包括核心算法步骤和实现过程。

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

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

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

解题思路:
先序遍历的第一个结点一定是根节点,查找根节点在中序遍历数组中的位置,前面的结点便是左子树,后面的便是右子树,然后递归构造完整树。

参考链接 :
http://www.cnblogs.com/x1957/p/3519452.html

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
     public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length == 0 || inorder.length == 0)
            return null;
        TreeNode root = new TreeNode(preorder[0]);
        if(preorder.length == 1 && inorder.length == 1)
            return root;
        for(int i = 0; i < inorder.length; i++){
            if(inorder[i] == preorder[0]){
                root.left = buildTree(assist(preorder,1,i),assist(inorder,0,i-1));
                root.right = buildTree(assist(preorder,i+1,preorder.length-1),assist(inorder,i+1,inorder.length-1));
            }
        }
        return root;
    }
    /*
     *   辅助函数,用来切割数组
     */
    public int[] assist(int[] array,int start,int end){
        int[] res = new int[end-start+1];
        for(int i = start; i <= end; i++){
            res[i-start] = array[i];
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值