思路
利用horizontal distance(下面简称hd)来解。根节点为0,left child = 0-1,right child = 0+1,以此类推。对树进行bfs,根据hd为key将所有hd相同的节点存到一个list中作为value,然后根据hd从小到大依次输出即可。
关于horizontal distance
见https://www.youtube.com/watch?v=V7alrvgS5AI
和https://www.geeksforgeeks.org/bottom-view-binary-tree/
代码
• 实现1
使用一个map来记录每个节点的hd值,使用两个变量minHd和maxHd来记录当前最大和最小的hd,这样就不用在最后对map的键进行排序操作了。minHd和maxHd初始化都应该是0。
• • code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null)
return res;
Map<TreeNode,Integer> hd = new HashMap<>();
Map<Integer,List<Integer>> result = new HashMap<>();
Queue<TreeNode> queue = new LinkedList<>();
int minHd = 0, maxHd = 0;
queue.offer(root);
hd.put(root,0);
// bfs
while(!queue.isEmpty()) {
TreeNode cur = queue.poll();
int curHd = hd.get(cur);
result.putIfAbsent(curHd,new ArrayList<>());
result.get(curHd).add(cur.val);
if(cur.left != null) {
queue.offer(cur.left);
int leftHd = curHd - 1;
hd.put(cur.left,leftHd);
// update minHd
if(leftHd < minHd)
minHd = leftHd;
}
if(cur.right != null) {
queue.offer(cur.right);
int rightHd = curHd + 1;
hd.put(cur.right,rightHd);
// update maxHd
if(rightHd > maxHd)
maxHd = rightHd;
}
}
for(int i = minHd; i <= maxHd; i++) {
res.add(result.get(i));
}
return res;
}
}
• • 复杂度
时间复杂度O(2n) = O(n), 空间复杂度O(n)
• 实现2
(jiuzhang)使用一个队列记录hd值,一个队列用于bfs,但是最后需要进行获取键的最大/最小值。
• • code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// 实现2:借助collections.max/min
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null)
return res;
Map<Integer,List<Integer>> hash = new HashMap<>();
Queue<TreeNode> queue_node = new LinkedList<>();
Queue<Integer> queue_hd = new LinkedList<>();
queue_node.offer(root);
queue_hd.offer(0);
// bfs
while(!queue_node.isEmpty()) {
int hd = queue_hd.poll();
TreeNode node = queue_node.poll();
hash.putIfAbsent(hd,new ArrayList<>());
hash.get(hd).add(node.val);
if(node.left != null) {
queue_hd.offer(hd-1);
queue_node.offer(node.left);
}
if(node.right != null) {
queue_hd.offer(hd+1);
queue_node.offer(node.right);
}
}
int minHd = Collections.min(hash.keySet());
int maxHd = Collections.max(hash.keySet());
for(int i = minHd; i <= maxHd; i++) {
res.add(hash.get(i));
}
return res;
}
}
• • 复杂度
时间复杂度O(4n) = O(n), 因为collectons.max/min耗时均为O(n)
空间复杂度O(n)
两种写法的优缺点分析
实现1:时间稍快,但是空间耗费稍微多一些(map需要2倍queue的空间)
实现2:时间稍慢,但是空间耗费少一些(理由同上)