题解 | 二叉树遍历

二叉树遍历

https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef

import java.util.Scanner;

class TreeNode{
        char val;
        TreeNode left;
        TreeNode right;
        public TreeNode(char val){
            this.val=val;
        }
    }

public class Main {

    
    public static void show(TreeNode root){
        if(root==null){
            return;
        }
        show(root.left);
        System.out.print(root.val+" ");
        show(root.right);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
           TreeNode root=null;
           String str=in.nextLine();
           char[]ch=str.toCharArray();
           root=create(ch);
           show(root);
        }
    }
    
    public static int i=0;
    public static TreeNode create(char[] ch){
        TreeNode root=null;
        if(ch[i]!='#'){
            root=new TreeNode(ch[i]);
            i++;
            root.left=create(ch);
            root.right=create(ch);
        }else{
            i++;
        }
        return root;
    }
}

全部评论

相关推荐

09-25 18:40
已编辑
河北大学 Unity3D客户端
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务