Problem:
Given a binary tree, return the vertical order traversal of its nodes values.
For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1).
Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates).
If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.
Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.
Explanation:
以一棵树的根节点为(0,0),左孩子为(-1,-1),右孩子为(1,-1),依次类推,纵向遍历树,即横坐标相同的为一组。
My Thinking:
My Solution:
Optimum Thinking:
使用一个location类保存结点位置信息
Optimum Solution:
class Solution {
List<Location> locations=new ArrayList();
public List<List<Integer>> verticalTraversal(TreeNode root) {
traversal(root,0,0);//构建位置信息列表
Collections.sort(locations);//对列表按照自定义排序方式进行排序
List<List<Integer>> result=new ArrayList<>();
result.add(new ArrayList<Integer>());
int prev = locations.get(0).x;
for (Location loc: locations) {
if (loc.x != prev) {
prev = loc.x;
result.add(new ArrayList<Integer>());
}
result.get(result.size() - 1).add(loc.val);
}
return result;
}
public void traversal(TreeNode root,int x,int y){//为每个结点构建一个位置信息
if(root==null)
return;
locations.add(new Location(x,y,root.val));
traversal(root.left,x-1,y+1);
traversal(root.right,x+1,y+1);
}
}
class Location implements Comparable<Location>{//位置信息类,重写compareto方法用于比较
int x, y, val;
Location(int x, int y, int val) {
this.x = x;
this.y = y;
this.val = val;
}
@Override
public int compareTo(Location that) {
if (this.x != that.x)
return Integer.compare(this.x, that.x);
else if (this.y != that.y)
return Integer.compare(this.y, that.y);
else
return Integer.compare(this.val, that.val);
}
}