199. Binary Tree Right Side View

https://leetcode.com/problems/binary-tree-right-side-view/

https://leetcode.com/problems/binary-tree-right-side-view/discuss/56012/My-simple-accepted-solution(JAVA)
DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private void rightView(TreeNode cur, List<Integer> ans, int depth){
if(cur==null) return;
if(ans.size()==depth) ans.add(cur.val);
rightView(cur.right,ans,depth+1);
rightView(cur.left,ans,depth+1);
}
public List<Integer> rightSideView(TreeNode root) {
List<Integer> ans=new ArrayList<>();
rightView(root,ans,0);
return ans;
}
}

0%