题解 | #二叉树遍历#递归建树,再中序递归遍历就行。

二叉树遍历

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

import java.util.Scanner;
public class Main {
    private static int index = 0;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String s = sc.next();
            TreeNode root = buildTree(s);
            inOrder(root);
            System.out.println();
        }
    }
    private static TreeNode buildTree(String s) {
        char c = s.charAt(index++);
        if (c == '#') return null;
        TreeNode root = new TreeNode(c);
        root.left = buildTree(s);
        root.right = buildTree(s);
        return root;
    }
    private static void inOrder(TreeNode root) {
        if (root == null) return;
        inOrder(root.left);
        System.out.print(root.value + " ");
        inOrder(root.right);
    }
    private static class TreeNode {
        private final char value;
        private TreeNode left, right;
        private TreeNode(char value) {
            this.value = value;
            this.left = null;
            this.right = null;
        }
    }
}

全部评论

相关推荐

仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
05-29 09:02
门头沟学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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