yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #366. Find Leaves of Binary Tree #282

Open yokostan opened 5 years ago

yokostan commented 5 years ago
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> findLeaves(TreeNode root) {
        height(root);
        return res;
    }

    public int height(TreeNode node) {
        if (node == null) return -1;
        int level = 1 + Math.max(height(node.left), height(node.right));
        if (res.size() < level + 1) res.add(new ArrayList<>());
        res.get(level).add(node.val);
        return level;
    }
}