一道老题了啊。。。思路大概如下。。实现起来还是要细心的
1,层序遍历,通过一个Queue来收集所有的Node,同时需要同样一个Quene,来收集所有匹配的level
2,通过while(queue.isEmpty()) 来一直pop出一个一头元素,相应信息要进入到map中去,然后根据该元素节点,时候有左,右子树来进行,继续添加node和level信息
便利结束后,所有节点信息都收到map中了。。
然后根据map的key值从小到大,一次取出,放入result即可。。。
代码如下:
/**
* 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;
Map<Integer, List<Integer>> map = new HashMap<>(); // <col, list<root.val>>
Queue<TreeNode> nodeQ = new LinkedList<>();
Queue<Integer> colQ = new LinkedList<>();
nodeQ.add(root);
colQ.add(0);
int min=0;
int max=0;
while(!nodeQ.isEmpty()){
TreeNode node= nodeQ.poll();
int col= colQ.poll();
if(!map.containsKey(col)) map.put(col, new ArrayList<Integer>());
map.get(col).add(node.val);
if(node.left!=null){
nodeQ.add(node.left);
colQ.add(col-1);
min=Math.min(min, col-1);
}
if(node.right!=null){
nodeQ.add(node.right);
colQ.add(col+1);
max=Math.max(max, col+1);
}
}
for(int i=min; i<=max; i++){
result.add(map.get(i));
}
return result;
}
}
// 2.1.17
// 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上。。
今天写的,有点困了。。准备睡觉去。。。
/**
* 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>> list = new ArrayList<>();
if(root==null) return list;
Map<Integer, List<Integer>> map= new HashMap<Integer, List<Integer>>();
Queue<TreeNode> nodeQ= new LinkedList<>();
Queue<Integer> levelQ= new LinkedList<>();
nodeQ.add(root);
levelQ.add(0);
int min=0;
int max=0;
while(!nodeQ.isEmpty()){
TreeNode curr= nodeQ.poll(); // 一气呵成!!可惜这一个bug啊!!queue没有pop,是poll!pop是弹出,poll是抽签 stack是弹夹才是pop的爆发式,而queue是规矩排队,就一个个安静的抽取出来。。。
int level= levelQ.poll();
if(!map.containsKey(level)) map.put(level, new ArrayList<Integer>());
map.get(level).add(curr.val);
if(curr.left!=null){
min=Math.min(min, level-1);
nodeQ.add(curr.left);
levelQ.add(level-1);
}
if(curr.right!=null){
max=Math.max(max, level+1);
nodeQ.add(curr.right);
levelQ.add(level+1);
}
}
for(int i=min; i<=max; i++){
list.add(map.get(i));
}
return list;
}
}