h****3 发帖数: 89 | 7 多谢楼组分享,自己写了一个java版本的
public static void printVertical(TreeNode root){
HashMap> map = new HashMap
Integer>>();
printVerticalHelper(root,0,map);
SortedSet keys = new TreeSet(map.keySet());
for(int key:keys){
List temp = map.get(key);
for(int i=0;i
System.out.print(temp.get(i)+" ");
}
System.out.println();
}
}
public static void printVerticalHelper(TreeNode root, int pos,HashMap<
Integer,List> map){
List item;
if(!map.containsKey(pos)){
item = new ArrayList();
}else{
item = map.get(pos);
}
item.add(root.val);
map.put(pos, item);
if(root.left!=null)
printVerticalHelper(root.left,pos-1,map);
if(root.right!=null)
printVerticalHelper(root.right,pos+1,map);
} |