Java straight forward recursive solution


  • 0
    I

    Have the recursive method return the depth of the current node and keep constructing the answer list. The code can be cleaner but I think it's pretty easy to get the idea.

        public List<List<Integer>> findLeaves(TreeNode root) {
            List<List<Integer>> answer = new ArrayList<>();
            if (root != null ) putInto(answer, root.val, Math.max(getDepth(root.left, answer), getDepth(root.right, answer)) + 1);
            return answer;
        }
        
        private int getDepth(TreeNode root, List<List<Integer>> answer) {
            if (root == null) return 0;
            int depth = Math.max(getDepth(root.left, answer), getDepth(root.right, answer)) + 1;
            putInto(answer, root.val, depth);
            return depth;
        }
        
        private boolean putInto(List<List<Integer>> answer, int val, int depth) {
            if (answer.size() < depth) {
                List<Integer> levelAnswer = new ArrayList<>();
                levelAnswer.add(val);
                answer.add(levelAnswer);
            } else {
                answer.get(depth - 1).add(val);
            }
            return true;
        }
    
    

Log in to reply
 

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