1ms Recursive Java solution... Make use of level information and traverses data -> right -> left


  • 0
    M
    public List<Integer> rightSideView(TreeNode root) {
            
            List<Integer> rightView = new ArrayList<Integer>();        
            dfs(root, rightView, 0);
            return rightView;
        }
        
        public void dfs(TreeNode node, List<Integer> list, int level) {
            
            if (node == null) {
                return;
            }
            
            if (list.size() <= level) {
                list.add(node.val);
            }
            dfs(node.right, list, level + 1);
            dfs(node.left, list, level + 1);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.