Java DFS Concise


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

  • 0

    Similar logic to LC 102 Binary Tree Level Order Traversal.


Log in to reply
 

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