Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Examples:
Given binary tree
Given binary tree
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
return its vertical order traversal as:
[ [9], [3,15], [20], [7] ]
Given binary tree
[3,9,20,4,5,2,7]
,_3_ / \ 9 20 / \ / \ 4 5 2 7
return its vertical order traversal as:
[ [4], [9], [3,5,2], [20], [7] ]
Starting from root, given a node a label i, then it's left child (if not null) has a label i - 1 and it's right child (if not null) has a label i + 1. Traverse the tree using level order traversal and group all the nodes with the same label together.
public class VerticalOrderTraversal { public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> rst = new ArrayList<>(); if (root == null) { return rst; } Queue<TreeColumnNode> queue = new LinkedList<>(); queue.add(new TreeColumnNode(root, 0)); int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; Map<Integer, List<Integer>> labelSet = new HashMap<>(); while (!queue.isEmpty()) { TreeColumnNode curr = queue.poll(); if (!labelSet.containsKey(curr.label)) { labelSet.put(curr.label, new ArrayList<>()); } labelSet.get(curr.label).add(curr.node.val); min = Math.min(curr.label, min); max = Math.max(curr.label, max); if (curr.node.left != null) { queue.add(new TreeColumnNode(curr.node.left, curr.label - 1)); } if (curr.node.right != null) { queue.add(new TreeColumnNode(curr.node.right, curr.label + 1)); } } for (int i = min; i <= max; i++) { rst.add(labelSet.get(i)); } return rst; } private class TreeColumnNode { TreeNode node; int label; public TreeColumnNode(TreeNode node, int label) { this.node = node; this.label = label; } } }
No comments:
Post a Comment