/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if(root==null) return result;
Queue<TreeNode> nodeQ = new LinkedList<>(); // have a clear idea of what nodeQ contains.
Queue<Integer> levelQ = new LinkedList<>(); // have a clear idea of what levelQ contains.
Map<Integer, List<Integer>> map = new HashMap<>(); // have a clear idea of what map contains.
nodeQ.add(root);
levelQ.add(0);
int min=0;
int max=0;
while(!nodeQ.isEmpty()){ // while(nodeQ!=null) is wrong!! should check whether it is empty.
TreeNode node=nodeQ.poll();
int level=levelQ.poll();
if(!map.containsKey(level)) map.put(level, new ArrayList<Integer>());
map.get(level).add(node.val); // have a clear idea of what map contains.
if(node.left!=null){
nodeQ.add(node.left);
levelQ.add(level-1);
min=Math.min(min, level-1);
}
if(node.right!=null){
nodeQ.add(node.right);
levelQ.add(level+1);
max=Math.max(max, level+1);
}
// for the above two if() statements only if we have some in either left or right child, we add the child to the Q, otherwise need to do nothing.
}
for(int i=min; i<=max; i++){
result.add(map.get(i));
}
return result;
}
}
// have no idea about the question in the beginning, but after looking through solutions I immediately get the idea, it is the BFS approach. Did I know BFS?? Of course!!! You did many quesitons on BFS, basically it is reading elems on same level of tree, and then move to the next level.
// here there are many things for me to 总结, such as using Queue<> (Interface) and LinkedList<>(class) to track the information on each level. ALSO, understanding this question and transfering it to some simple questions and easy solutions is a good practice. Lastly, knowing using min, max to keep record of the range is the key point to this question!! 一会好好总结在ppt上。。
这道题,虽然代码略多,但是思路还是非常清晰简练的。。。相信读者看代码就能知道我什么意思。。