L2-011 玩转二叉树

本題主要要解決的只有兩個問題

一個是通過前序遍歷和中序遍歷得出原二叉樹

二時對樹層序遍歷

其實與其説是對樹的鏡像遍歷,我們完全可以不用管他的鏡像,只需改一下層序遍歷的順序即可

import java.io.BufferedInputStream;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class HeroNode{
    int data;
    HeroNode left,right;
}
public class Main {
   public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n=scan.nextInt();
        int[]in=new int[n+1];
        int[]pre=new int[n+1];
        for(int i=0;i<n;i++){
            in[i]=scan.nextInt();
        }
        for(int i=0;i<n;i++){
            pre[i]=scan.nextInt();
        }
        HeroNode root=BuildTree(in,0,pre,0,n);
        LevelOrder(root);
    }
    public static HeroNode BuildTree(int[]in,int is,int[]pre,int ps,int n){
        if(n<=0)
            return null;
        HeroNode heroNode=new HeroNode();
        heroNode.data=pre[ps];
        int i;
        for(i=0;i<n;i++){
            if(in[i+is]== heroNode.data)
                break;
        }
        heroNode.left=BuildTree(in,is,pre,ps+1,i);
        heroNode.right=BuildTree(in,i+1+is,pre,ps+i+1,n-1-i);
        return heroNode;
    }
    public static void LevelOrder(HeroNode node){
        boolean isFlag=false;
        HeroNode current=node;
        if(current==null)
            return;
        Queue<HeroNode>queue=new LinkedList<HeroNode>();
        queue.offer(current);
        while(!queue.isEmpty()){
            current=queue.poll();
            if(isFlag==false){
                System.out.print(current.data);
                isFlag=true;
            }else{
                System.out.print(" "+current.data);
            }
            if(current.right!=null){//因爲是對鏡像進行層序,所以只需把存入隊列的順序調換即可
                queue.offer(current.right);
            }
            if(current.left!=null){
                queue.offer(current.left);
            }
        }
    }
}

此外,本體還有不用建樹的方法:

(2条消息) L2-011 玩转二叉树 (25分)java解析_咿呀咿呀咿呀哟的博客-CSDN博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值