199. Binary Tree Right Side View

Given the root of 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 1:

Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]

public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
helper(root, result, 0);
return result;
}

public void helper(TreeNode curr, List<Integer> result, int currDepth) {
if (curr == null) {
return;
}
if (currDepth == result.size()) {
result.add(curr.val);
}
helper(curr.right, result, currDepth + 1);
helper(curr.left, result, currDepth + 1); // 对左子树也需要遍历,eg:跟节点只有个左子树,那么左子树也要加到list中
}
posted @ 2022-11-23 23:34  MarkLeeBYR  阅读(18)  评论(0)    收藏  举报