• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
不会投篮的邢
投篮三不沾
博客园    首页    新随笔    联系   管理    订阅  订阅

牛客-二叉树遍历

题目描述

编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。

输入描述:

输入包括1行字符串,长度不超过100。

输出描述:

可能有多组测试数据,对于每组数据,
输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。
每个输出结果占一行。
示例1

输入

复制
abc##de#g##f###

输出

复制
c b e g d f a 
import java.util.Scanner;
public class Main{
    public static int index;
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            String s = in.next();
            index = 0;
            Node node = Tree(s);
            preOrder(node);
        }
    }
    public static Node Tree(String s){
        Node root = new Node(s.charAt(index));
        index++;
        if(root.s=='#'){
            return root;
        }else{
            root.left = Tree(s);
            root.right = Tree(s);
            return root;
        }
    }
    //中序遍历
    public static void preOrder(Node L){
        if(L!=null){
            preOrder(L.left);
            if(L.s!='#')
                System.out.print(L.s+" ");
            preOrder(L.right);
        }
    }
}
class Node{
    char s;
    Node left;
    Node right;
    public Node(){
    }
    public Node(char s){
        this.s = s;
        this.left = null;
        this.right = null;
    }
    public Node(char s, Node left, Node right){
        this.left = left;
        this.right = right;
        this.s = s;
    }
}

  

posted @ 2021-03-08 22:16  不会投篮的邢  阅读(76)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3