题目:
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例 1:
输入: [1,2,3,null,5,null,4]
输出: [1,3,4]
示例 2:
输入: [1,null,3]
输出: [1,3]
示例 3:
输入: []
输出: []
提示:
二叉树的节点个数的范围是 [0,100]
-100 <= Node.val <= 100
代码一:BFS
class Solution {
public List<Integer> rightSideView(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
q.offer(root);
int count = q.size();
while (!q.isEmpty()) {
TreeNode node = q.poll();
count--;
if (node.left != null) {
q.offer(node.left);
}
if (node.right != null) {
q.offer(node.right);
}
if (count == 0) {
count = q.size();
list.add(node.val);
}
}
return list;
}
}
代码二:DFS
// DFS
class Solution1 {
// 定义集合用来记录结果
List<Integer> list = new ArrayList<>();
int nowDepth = 0;
public List<Integer> rightSideView(TreeNode root) {
if (root == null) {
return list;
}
dfs(root, 1);
return list;
}
public void dfs(TreeNode root, int depth) {
if (root == null) {
return;
}
if (nowDepth < depth) {
list.add(root.val);
nowDepth = depth;
}
dfs(root.right, depth+1);
dfs(root.left, depth+1);
}
}
解题思路:
和上两道题大致一样的思路,注意右节点的处理时机,每层遍历的最后一个出队的节点就是每层最右边的节点。
注意:
锻炼身体。