leetcode 107. Binary Tree Level Order Traversal II
- Binary Tree Level Order Traversal II:题目链接
BFS
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 35 36 37 38 39 40 41
|
class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> res= new ArrayList<>(); if (root == null) { return res; } Queue<TreeNode> queue = new LinkedList<>(); Stack<List<Integer>> stack = new Stack<>(); queue.offer(root); while (!queue.isEmpty()) { List<Integer> list = new ArrayList<>(); for (int size = queue.size(); size > 0; --size) { TreeNode front = queue.poll(); list.add(front.val); if (front.left != null) { queue.offer(front.left); } if (front.right != null) { queue.offer(front.right); } } stack.push(list); } while (!stack.isEmpty()) { res.add(stack.pop()); } return res; } }
|