BFS
使用一个队列,从左向右遍历每一层,将每层最右侧的节点值加入答案当中
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> ans = new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) {
if (root == null) return ans;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
TreeNode cur = queue.poll();
if (cur.left != null)
queue.offer(cur.left);
if (cur.right != null)
queue.offer(cur.right);
if (i == levelSize - 1)
ans.add(cur.val);
}
}
return ans;
}
}
dfs
以 根节点->右节点->左节点的顺序遍历二叉树,将每一层遍历得到的第一个节点加入答案列表中
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> ans = new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) {
if (root == null) return ans;
dfs(root, 0);
return ans;
}
private void dfs(TreeNode root, int depth) {
if (root == null)
return;
// 如果当前节点的深度还没有出现在结果列表中则该节点是第一个被访问的节点
if (depth == ans.size())
ans.add(root.val);
depth++;
dfs(root.right, depth);
dfs(root.left, depth);
}
}