震惊!这二叉树竟然不能用List做广度优先遍历?

 


public class Main {


    static class TreeNode {
        private final String name;
        private TreeNode left;
        private TreeNode right;

        public TreeNode(String name) {
            this.name = name;
        }
    }

    public static void main(String[] args) {
        TreeNode t3_1 = new TreeNode("3-1");
        TreeNode t3_2 = new TreeNode("3-2");
        TreeNode t3_3 = new TreeNode("3-3");
        TreeNode t3_4 = new TreeNode("3-4");

        TreeNode t2_1 = new TreeNode("2-1");
        TreeNode t2_2 = new TreeNode("2-2");

        TreeNode t1 = new TreeNode("1-1");

        t1.left = t2_1;
        t1.right = t2_2;

        t2_1.left = t3_1;
        t2_1.right = t3_2;

        t2_2.left = t3_3;
        t2_2.right = t3_4;

        bfsWithQueue(t1);
        System.out.println("------------");
        bfsWithList(t1);
    }

    public static void bfsWithQueue(TreeNode head) {
        Queue<TreeNode> q = new LinkedList<>();

        q.add(head);
        while (!q.isEmpty()) {
            TreeNode n = q.poll();
            System.out.println(n.name);
            if (n.left != null) {
                q.add(n.left);
            }
            if (n.right != null) {
                q.add(n.right);
            }
        }
    }

    /**
    这个list成精了,竟然敢参与二叉树的遍历?
    */

    public static void bfsWithList(TreeNode head) {

        List<TreeNode> nodes = new LinkedList<>();
        nodes.add(head);


        while (nodes.size() > 0) {
            List<TreeNode> children = new LinkedList<>();
            nodes.forEach(n -> {
                System.out.println(n.name);
                if (n.left != null) {
                    children.add(n.left);
                }
                if (n.right != null) {
                    children.add(n.right);
                }
            });
            nodes = children;
        }
    }

}

如何做一个好面试官?

1.候选人都是菜逼,出得方案都是垃圾

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页