199. 二叉树的右视图
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
PS:
1层序遍历
2递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int count = queue.size();
while(count > 0){
count--;
TreeNode cur = queue.poll();
if(count == 0){
//只有上一层的最后一个才能加入res
//如果右面有,就是右面
//右面没有,左面就是上一层的最后一个
res.add(cur.val);
}
//先加左面,先poll左面
if(cur.left != null){
queue.add(cur.left);
}
if(cur.right != null){
queue.add(cur.right);
}
}
}
return res;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int[] max = {0};
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
helper(res, root, 1);
return res;
}
private void helper(List<Integer> res,TreeNode treeNode, int deep) {
if (treeNode == null) {
return;
}
if (deep > max[0]) {
max[0] = deep;
res.add(treeNode.val);
}
helper(res, treeNode.right, deep + 1);
helper(res, treeNode.left, deep + 1);
}
}