前序遍历二叉树

这道题要用到递归是肯定的,但是如果掌握的库函数够多还是可以简化代码的。

首先讲一下最简单的,不知道数组的copy函数的情况下,最简单的做法:

多写一个函数,肯定是必要的。

主要注意要控制好下标的计算,不然很容易出错。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        return constructNode(pre,in,0,pre.length,0,in.length);
    }
    TreeNode constructNode(int []pre,int []in,int startPre,int endPre,int startIn,int endIn){
        if(startPre == endPre){
            return null;
        }
        TreeNode treeNode = new TreeNode(pre[startPre]);
        int parentIndex = startPre;
        for(int i = startIn;i < endIn;i++){
            if(in[i] == pre[startPre]){
                parentIndex = i;
                break;
            }
        }
        treeNode.left = constructNode(pre,in,startPre+1,startPre+1+parentIndex-startIn,
                                      startIn,parentIndex);
        treeNode.right = constructNode(pre,in,startPre+parentIndex-startIn+1,endPre,parentIndex + 1,endIn);
        return treeNode;
    }
}

最简单做法,使用库函数copy。

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

public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre.length != in.length || 0 == pre.length){
            return null;
        }
        TreeNode treeNode = new TreeNode(pre[0]);
        
        for(int i = 0;i < in.length;i++){
            if(pre[0] == in[i]){
                treeNode.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,1 + i),Arrays.copyOfRange(in,0,i));
                treeNode.right = reConstructBinaryTree(Arrays.copyOfRange(pre,1+i,pre.length),Arrays.copyOfRange(in,i+1,in.length));
            }
        }
     return treeNode;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值