题解 | #二叉树遍历#

二叉树遍历

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

容易理解的递归创建方式


import java.util.Scanner;

class TreeNode1{
    public char val;
    public TreeNode1 left;
    public TreeNode1 right;

    public TreeNode1(char val) {
        this.val = val;
    }
}



public class Main {
    public static int i = 0;
    public static TreeNode1 createTree(String str){
        TreeNode1 root = null;
        
        if (str.charAt(i) != '#') {
            root = new TreeNode1(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        } else {
            i++;
        }
        return root;
    }

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


    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (scan.hasNextLine()) {
            String str = scan.nextLine();
            TreeNode1 root = createTree(str);
            inOrderTraversal(root);
        }

    }
}


全部评论

相关推荐

05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

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