Topic Address:
https://leetcode.com/problems/binary-tree-right-side-view/
Seeking a binary right to left, when seen in each of the first number. Direct BFS, then added to the last digit of each layer returns the final result. code show as below:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int len = queue.size();
for (int i = 0; i < len; i++) {
TreeNode x = queue.poll();
// i == len - 1说明已经遍历到了当层的最右边的节点
if (i == len - 1) {
res.add(x.val);
}
if (x.left != null) {
queue.offer(x.left);
}
if (x.right != null) {
queue.offer(x.right);
}
}
}
return res;
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
time complexity , the spatial complexity .