Description
Given 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:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <—
/
2 3 <—
\
5 4 <—
Solution
给一棵二叉树,返回这棵二叉树从右边看的从root到leaf的值。
We use an int depth to document the depth of we have travered. If depth is equal to size of res. We add the node’s value into res. It is kind like post order traversal. node->right-left order.
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
rightViewHelper(res, root, 0);
return res;
}
private void rightViewHelper(List<Integer> res, TreeNode node, int depth){
if (node == null){
return;
}
if (depth == res.size()){
res.add(node.val);
}
rightViewHelper(res, node.right, depth + 1);
rightViewHelper(res, node.left, depth + 1);
}
}
Time Complexity: O()
Space Complexity: O()