题目
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例 1:
输入: root = [1,2,3,null,5,null,4]
输出: [1,3,4]
解释:
题解
方式一:BFS
public List<Integer> rightSideView(TreeNode root) {
Deque<TreeNode> deque = new LinkedList<>();
List<Integer> result = new LinkedList<>();
if (root == null) return result;
deque.offer(root);
while (!deque.isEmpty()) {
int len = deque.size();
for (int i = 0; i < len; i++) {
TreeNode node = deque.poll();
if (node.left != null) deque.offer(node.left);
if (node.right != null) deque.offer(node.right);
if (i == len - 1) {
result.add(node.val);
}
}
}
return result;
}
方式二:DFS
public List<Integer> rightSideView(TreeNode root) {
Map<Integer, Integer> map = new HashMap<>();
int maxDepth = -1;
Stack<TreeNode> nodeStack = new Stack<>();
Stack<Integer> depthStack = new Stack<>();
nodeStack.push(root);
depthStack.push(0);
while (!nodeStack.isEmpty()) {
TreeNode node = nodeStack.pop();
int depth = depthStack.pop();
if (node != null) {
maxDepth = Math.max(maxDepth, depth);
if (!map.containsKey(depth)) { // 存当前深度的第一个节点
map.put(depth, node.val);
}
nodeStack.push(node.left);
nodeStack.push(node.right); // 栈结构,先取出的是right节点
depthStack.push(depth + 1);
depthStack.push(depth + 1);
}
}
List<Integer> result = new LinkedList<>();
for (int i = 0; i <= maxDepth; i++) {
result.add(map.get(i));
}
return result;
}
总结
算法:DFS、BFS