【剑指offer】已知二叉树的前序和中序,重建二叉树(java)

本文分享了一种实现层序遍历二叉树的方法,包括重建二叉树的算法和非递归代码。作者详细介绍了如何使用前序和中序遍历数组重建二叉树,并通过队列实现层序遍历,最终成功打印二叉树结构。

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

写的真费劲!!!!

我就是一道酸菜鱼,又酸,又菜,还多余

终于写出来了层序遍历二叉树,可以正常打印二叉树了;2019.3.1

public class Solution {
   public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        return  reConstructBT(0,pre.length-1,0,in.length-1,pre,in);
    }
    private TreeNode reConstructBT(int preStart,int preEnd,int inStart,int inEnd,int[] pre,int[] in){
        TreeNode root = new TreeNode(pre[preStart]);
        root.left = null;
        root.right = null;
        if(preStart == preEnd||inStart == inEnd){
            return root;
        }
        int a = pre[preStart];
        int index1 = getIndex(in,a);
        int leftLength = index1 - inStart;
        int rightLength = inEnd - index1;
        if(leftLength>0){
            root.left = reConstructBT(preStart+1,preStart+leftLength,inStart,index1-1,pre,in);
        }
        if(rightLength>0){
            root.right = reConstructBT(preStart+leftLength+1,preEnd,index1+1,inEnd,pre,in);
        }
        return(root);
    }
    public static int getIndex(int[] arr, int value) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == value) {
                return i;
            }
        }
        return -1;
    }
}

下面的代码是我自己在本地IDEA中测试重建二叉树的,层序遍历打印二叉树,非递归代码。

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
public class BinaryTree {
    public static void main(String[] args){
        int[] in ={3,2,4,1,6,5,7};
        int[] pre ={1,2,3,4,5,6,7};
        BinaryTree BT =  new BinaryTree();
        TreeNode root = BT.reConstructBinaryTree(pre,in);
        ArrayList<Integer> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if(root ==null){
            System.out.println("二叉树为空");
        }else{
            queue.offer(root);
            while(!queue.isEmpty()){
                TreeNode root1 = queue.poll();
                if (root1.left!=null){
                    queue.offer(root1.left);
                }
                if (root1.right!=null){
                    queue.offer(root1.right);
                }
                list.add(root1.val);
            }
        }
        for(int i:list){
            System.out.println(i);
        }
    }
    //此处加上上文Solution内的代码
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值