题目地址:
https://www.lintcode.com/problem/binary-tree-right-side-view/description
给定一棵二叉树,返回其从右向左看时看到的所有节点。
法1:BFS。分层遍历即可,每次都将最右边的值加入最终结果。代码如下:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Solution {
/**
* @param root: the root of the given tree
* @return: the values of the nodes you can see ordered from top to bottom
*/
public List<Integer> rightSideView(TreeNode root) {
// write your code here
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
// 分层遍历需要记录一下队列的size
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode x = queue.poll();
if (i == 0) {
res.add(x.val);
}
// 先加右儿子再加左儿子,这样每层第一个节点就可以直接加入res
if (x.right != null) {
queue.offer(x.right);
}
if (x.left != null) {
queue.offer(x.left);
}
}
}
return res;
}
}
class TreeNode
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
时空复杂度 O ( n ) O(n) O(n)。
法2:DFS。可以将当前节点深度作为参数在递归时传递下去,并且按照先序遍历的顺序做DFS。如果是第一次遍历到某一深度,则将节点的值直接加入res,否则覆盖res在当前深度的值。代码如下:
import java.util.ArrayList;
import java.util.List;
public class Solution {
/**
* @param root: the root of the given tree
* @return: the values of the nodes you can see ordered from top to bottom
*/
public List<Integer> rightSideView(TreeNode root) {
// write your code here
List<Integer> res = new ArrayList<>();
dfs(root, 0, res);
return res;
}
private void dfs(TreeNode root, int depth, List<Integer> res) {
if (root == null) {
return;
}
// 如果是第一次遍历到depth这个深度,则直接将值加入res;
// 否则直接覆盖res中当前深度的值
if (depth == res.size()) {
res.add(root.val);
} else {
res.set(depth, root.val);
}
// 先遍历左子树,
dfs(root.left, depth + 1, res);
dfs(root.right, depth + 1, res);
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。