(specail) 314. Binary Tree Vertical Order Traversal
T: O(n)
S: O(n)
/**
* 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>> verticalOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Map<Integer, List<Integer>> map = new HashMap<>();
Queue<TreeNode> queue = new LinkedList<>();
Queue<Integer> colQueue = new LinkedList<>();
queue.offer(root);
colQueue.offer(0);
// for range!
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
int col = colQueue.poll();
map.computeIfAbsent(col, k -> new ArrayList<>()).add(cur.val);
min = Math.min(min, col);
max = Math.max(max, col);
if (cur.left != null) {
queue.offer(cur.left);
colQueue.offer(col-1);
}
if (cur.right != null) {
queue.offer(cur.right);
colQueue.offer(col+1);
}
}
for (int i = min; i <= max; i++) {
result.add(map.get(i));
}
return result;
}
}
/**
use another queue -> left put col - 1
right put col+1
T: O(n)
S: O(n)
*/
Previous971. Flip Binary Tree To Match Preorder TraversalNext(314 followup) 987. Vertical Order Traversal of a Binary Tree
Last updated