199. Binary Tree Right Side View
Given a binary tree, imagine yourself standing on therightside of it, return the values of the nodes you can see ordered from top to bottom.
1 <---
/ \
2 3 <---
\ \
5 4 <---
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
getRightSideView(root, 0, res);
return res;
}
public void getRightSideView(TreeNode node, int depth, List<Integer> res) {
if (node == null) {
return;
}
if (res.size() == depth) {
res.add(node.val);
}
getRightSideView(node.right, depth + 1, res);
getRightSideView(node.left, depth + 1, res);
}
}
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 size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode curNode = queue.remove();
if (i == size - 1) {
res.add(curNode.val);
}
if (curNode.left != null) {
queue.add(curNode.left);
}
if (curNode.right != null) {
queue.add(curNode.right);
}
}
}
return res;
}
}
3. Time & Space Complexity