1.题目描述:
给定一个二叉树的根节点root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
2.层序遍历:也可普通的层序遍历结束之后对list集合进行操作得到右视图。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> list = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if (root == null) return list;
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
TreeNode temp = queue.poll();
size--;
if (size == 0) list.add(temp.val);
if (temp.left != null) queue.offer(temp.left);
if (temp.right != null) queue.offer(temp.right);
}
}
return list;
}
}
3.递归,先访问右子树即可:
class Solution {
private List<Integer> list = new ArrayList<>();
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 (depth > list.size()) list.add(root.val);
dfs(root.right, depth + 1);
dfs(root.left, depth + 1);
}
}