ID | Title | Difficulty | |
---|---|---|---|
Loading... |
199. Binary Tree Right Side View
Medium
LeetCode
Tree, Depth-First Search, Breadth-First Search, Binary Tree
Problem
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
Code
/**
* 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;
helper(res, root, 0);
return res;
}
private void helper(List<Integer> res, TreeNode root, int level){
if(root == null) return;
// 保存当前树的等级
// 每个节点要能加入到结果的前提是必须属于这个等级的节点
// 但是是从右边看,因此要优先看看右子树有没有结果
if(res.size() == level){
res.add(root.val);
}
// 优先查找右子树
helper(res, root.right, level + 1);
helper(res, root.left, level + 1);
}
}
class Solution {
public List<Integer> rightSideView(TreeNode root) {
// reverse level traversal
List<Integer> result = new ArrayList();
Queue<TreeNode> queue = new LinkedList();
if (root == null) return result;
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
// 第一个元素是这一层最右边的元素
if (i == 0) result.add(cur.val);
// 相当于从右往左加入
if (cur.right != null) queue.offer(cur.right);
if (cur.left != null) queue.offer(cur.left);
}
}
return result;
}
}
按 <- 键看上一题!
198. House Robber
按 -> 键看下一题!
200. Number of Islands