BiruLyu
7/5/2017 - 8:42 PM

366. Find Leaves of Binary Tree.java

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