题目
https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof
解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { public List<List<Integer>> levelOrder(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); List<List<Integer>> res = new ArrayList<>(); boolean flag = true; if (root != null) queue.add(root); while (!queue.isEmpty()) { List<Integer> list = new ArrayList<>(); for (int i= queue.size(); i>0; i--) { TreeNode node = queue.poll(); list.add(node.val); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); }
if(!flag) list = reverse(list); flag = !flag; res.add(list); } return res; } public List<Integer> reverse(List<Integer> list){ List<Integer> res = new ArrayList<>(); for(int i = list.size()-1; i >= 0; i --){ res.add(list.get(i)); } return res; } }
|