easy short java DFS


  • 0
    R
    public class Solution {
        public List<List<Integer>> findLeaves(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if(root!=null)
                findLeaves(res, root);
            return res;
        }
        
        private int findLeaves(List<List<Integer>> res, TreeNode root) {
            int left = -1;
            int right = -1;
            if(root.left != null) {
                left = findLeaves(res, root.left);
            }
            if(root.right != null) {
                right = findLeaves(res, root.right);
            }
            int depth = Math.max(left, right) + 1;
            if(res.size() < depth + 1) {
                res.add(new ArrayList<>());
            }
            res.get(depth).add(root.val);
            return depth;
        }
    }
    

Log in to reply
 

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