【树】剑指Offer: 重建二叉树

【在线编程】重建二叉树

【问题描述】

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

【解题思路 & Java实现】

思路:分治法。因为前序遍历是 “根左右”,中序遍历是 “左根右”。所以从pre中第一个元素得到根root,然后在in中找到root的位置index,将 in 分为两部分,index左边为左子树,index右边为右子树。分别对左边和右边进行递归建树。

注意:

  1. 递归出口
  2. 递归时数组的下标如何确定?(根据“前序遍历和中序遍历的结点个数一定是相同的”来简单计算即可)

代码1: 借用 Arrays.copyOfRange(array, from. , to) 左闭右开

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.Arrays;

public class Solution {
    public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        if (pre.length == 0 || in.length == 0) {
            return null;
        }

        TreeNode root = new TreeNode(pre[0]);

        int index = 0;
        while (index < in.length && in[index] != root.val) {
            index++;
        }
        
        root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, index + 1), Arrays.copyOfRange(in, 0, index));
        root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, index + 1, pre.length), Arrays.copyOfRange(in, index + 1, in.length));
           
        return root;
    }
}

代码二:函数中传入下标来截取数组。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.Arrays;

public class Solution {
    public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        return reConstructBinaryTreeHandler(pre, 0, pre.length - 1, in, 0, in.length - 1);
    }
    
    public static TreeNode reConstructBinaryTreeHandler(int[] pre, int preLeft, int preRight, int[] in, int inLeft, int inRight) {

        //递归出口
        if (preLeft > preRight || inLeft > inRight) {
            return null;
        }

        TreeNode root = new TreeNode(pre[preLeft]);

        int index = 0;
        while (index < inRight && in[index] != root.val) {
            index++;
        }

        root.left = reConstructBinaryTreeHandler(pre, preLeft + 1, index - inLeft + preLeft, in, inLeft, index - 1);
        root.right = reConstructBinaryTreeHandler(pre, index - inLeft + preLeft + 1, preRight, in, index + 1, inRight);

        return root;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值