-
107. Binary Tree Level Order Traversal IIAlgorithm/java tip 2021. 3. 3. 22:24
leetcode.com/problems/binary-tree-level-order-traversal-ii/submissions/
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> ret = new ArrayList<>(); if(root == null) return ret; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); while(!q.isEmpty()) { List<Integer> level = new ArrayList<>(); int size = q.size(); for(int i=0; i<size; i++) { TreeNode node = q.poll(); level.add(node.val); if(node.left != null) q.offer(node.left); if(node.right != null) q.offer(node.right); } ret.add(0, level); } return ret; } }
q.offer() : insert
q.poll() : pop
q.peek() : getHead
coding-factory.tistory.com/603?category=758267
'Algorithm > java tip' 카테고리의 다른 글
[programmers] 더 맵게(heap) (0) 2021.03.06 [programmers] 소수 찾기 (0) 2021.03.05 46. Permutations (0) 2021.03.03 86. Partition List (0) 2021.03.03 Tip4 (0) 2020.04.19