199. Binary Tree Right Side View

以这个数举例,当层数等于result个数的时候,当前的值会被加入结果数组。递归时会先加入[1,3,4],然后递归到5的时候,发现当前的depthresult的大小不相等,所以不加入。

   1            <--- 0
 /   \
2     3         <--- 1
     / \
    5   4       <--- 2
public List<Integer> rightSideView(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    dfs(root, res, 0);
    return res;
}

public void dfs(TreeNode root, List<Integer> res, int depth) {
    if (root == null) return;

    if (res.size() == depth) 
        res.add(root.val);

    dfs(root.right, res, depth + 1);
    dfs(root.left, res, depth + 1);
}

results matching ""

    No results matching ""