My accepted Java solution.


  • 0
    Z
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<List<Integer>> findLeaves(TreeNode root) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            for(int i = 0; i< getHeight(root) ; i++) {
                res.add(new ArrayList());
            }
            findLeaves(root,res);
            return res;
        }
        
        public int findLeaves(TreeNode root,  List<List<Integer>> res) {
            if(root == null) return 0;
            int dist = Math.max(findLeaves(root.left,res) ,findLeaves(root.right,res) );
            res.get(dist).add(root.val);
            return dist + 1;
        }
        
        public int getHeight(TreeNode root) {
            if(root == null) return 0;
            return Math.max(getHeight(root.left), getHeight(root.right) ) + 1;
        }
    }

Log in to reply
 

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