107. 二叉樹的層序遍歷 II
阿新 • • 發佈:2021-01-02
傳送門
程式碼
class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> ans = new LinkedList<>(); if(root == null) return ans; Stack<List<Integer>> stack = new Stack<>(); Queue<TreeNode> que = new LinkedList<>(); que.offer(root); while(!que.isEmpty()) { int size = que.size(); List<Integer> list = new LinkedList<>(); for(int i = 0;i < size; ++i) { TreeNode t = que.poll(); if(t.left != null) que.offer(t.left); if(t.right != null) que.offer(t.right); list.add(t.val); } stack.add(list); } while(!stack.isEmpty()) { List<Integer> list = stack.pop(); ans.add(list); } return ans; } }
思路
層序遍歷哪就用佇列存下來每層的值,倒敘的話,就先用棧存,然後再轉移一下,返回即可。