JZ7 重建二叉树

在这里插入图片描述

import java.util.*;
/**
 * 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 [] vin) {
        return func(pre,vin,0,pre.length-1,0,vin.length-1);
    }
    
    public TreeNode func(int[] pre,int[] in,int left_pre,int right_pre,int left_in,int right_in){
        if(left_pre>=pre.length||left_in>=in.length||left_pre>right_pre||left_in>right_in)
            return null;
        int value = pre[left_pre];
        TreeNode node = new TreeNode(value);
        //确定根结点 即node本身
        //根结点的value是先序遍历中的最左端的那个
        
        // pre: [1] [2 4 7] [3 5 6 8]
        // in : [4 7 2] [1] [5 3 8 6]
        int count = left_in;
        //在中序遍历中寻找count的位置并且计算长度
        while(in[count] != value){
            count++;
        }//注意count不是从0开始的,而是从left_pre开始的
        //找到位置以后计算长度 
        //比如针对247分析:
        /*
         pre:[1] 2 4 7 3 5 6 8
         in:  4  7 2[1]5 3 8 6
              0  1 2 3 4 5 6 7
              
        */
        count = count-left_in;//count为长度
        
        node.left = func(pre,in,left_pre+1,left_pre+count,left_in,right_in+count-1);
        node.right = func(pre,in,left_pre+count+1,right_pre,left_in+count+1,right_in);

        
        return node;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值