题目地址
https://binarysearch.com/problems/Top-View-of-a-Tree/editorials/3045073
题目描述
思路一
- 层次遍历二叉树,队列中除了存放节点外,还要存放当前节点的横坐标
- 用哈希表记录横坐标对应的节点值,只有横坐标未出现过才会更新哈希表
- 对哈希表中的key进行排序,按顺序将val加入结果res中
代码(Python)
class Solution:
def solve(self, root):
queue = [(root, 0)]
hashmap = {}
while queue:
node, x = queue.pop(0)
if x not in hashmap:
hashmap[x] = node.val
if node.left:
queue.append((node.left, x - 1))
if node.right:
queue.append((node.right, x + 1))
return [val for key, val in sorted(hashmap.items())]
代码(Java)
class Solution {
public int[] solve(Tree root) {
Queue<Tree> queueNode = new LinkedList<>();
Queue<Integer> queueXs = new LinkedList<>();
Map<Integer,Integer> map = new HashMap<>();
queueNode.offer(root);
queueXs.offer(0);
while(!queueNode.isEmpty()){
Tree node = queueNode.poll();
int x = queueXs.poll();
if(!map.containsKey(x)){
map.put(x,node.val);
}
if(node.left != null){
queueNode.offer(node.left);
queueXs.offer(x - 1);
}
if(node.right != null){
queueNode.offer(node.right);
queueXs.offer(x + 1);
}
}
Integer[] keys = map.keySet().toArray(new Integer[0]);
Arrays.sort(keys);
int[] res = new int[map.size()];
for(int i = 0; i < res.length; i++){
res[i] = map.get(keys[i]);
}
return res;
}
}
复杂度分析
- 时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn)
- 空间复杂度: O ( n ) O(n) O(n)
思路二
其实哈希表里记录的横坐标都是连续的整数,记录横坐标的最小值min_x,就可以避免对哈希表key的排序
不过感觉排不排序的差不太多,对Java好像明显一点
代码(Python)
class Solution:
def solve(self, root):
queue = [(root, 0)]
hashmap = {}
min_x = 0
while queue:
node, x = queue.pop(0)
if x not in hashmap:
hashmap[x] = node.val
min_x = min(min_x, x)
if node.left:
queue.append((node.left, x - 1))
if node.right:
queue.append((node.right, x + 1))
return [hashmap[min_x + i] for i in range(len(hashmap))]
代码(Java)
class Solution {
public int[] solve(Tree root) {
Queue<Tree> queueNode = new LinkedList<>();
Queue<Integer> queueXs = new LinkedList<>();
Map<Integer,Integer> map = new HashMap<>();
int minX = 0;
queueNode.offer(root);
queueXs.offer(0);
while(!queueNode.isEmpty()){
Tree node = queueNode.poll();
int x = queueXs.poll();
if(!map.containsKey(x)){
map.put(x,node.val);
minX = Math.min(minX, x);
}
if(node.left != null){
queueNode.offer(node.left);
queueXs.offer(x - 1);
}
if(node.right != null){
queueNode.offer(node.right);
queueXs.offer(x + 1);
}
}
int[] res = new int[map.size()];
for(int i = 0; i < res.length; i++){
res[i] = map.get(minX + i);
}
return res;
}
}
复杂度分析
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)