面试题32 - III. 从上到下打印二叉树 III

前面一道题的变种,加个就判断,然后选择是否翻转集合就行了

class Solution {
 public List> levelOrder(TreeNode root) {
        List> lists = new ArrayList<>();

        LinkedList treeNodes = new LinkedList<>();
        treeNodes.add(root);
        treeNodes.add(null);
        boolean flag = false;


        while (!treeNodes.isEmpty()) {
            ArrayList list = new ArrayList<>();

            TreeNode node = treeNodes.removeFirst();
            if (node == null) break;

            while (node != null) {
                list.add(node.val);
                if (node.left != null) treeNodes.add(node.left);
                if (node.right != null) treeNodes.add(node.right);
                node = treeNodes.removeFirst();
            }

            treeNodes.add(null);

            if (flag) {
                Collections.reverse(list);
            }
            flag = !flag;
            lists.add(list);


        }

        return lists;
    }
}

 

你可能感兴趣的:(剑指offer)