congr / world

2 stars 1 forks source link

LeetCode : 366. Find Leaves of Binary Tree #498

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/find-leaves-of-binary-tree/

image image

congr commented 5 years ago

O(N^2) in worst case.

/**
 * 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>> findLeaves(TreeNode root) {
        List<List<Integer>> lists = new ArrayList();
        if (root == null) return lists;

        while (root != null) {
            List<Integer> list = new ArrayList();
            lists.add(list);
            root = find(root, list); // !!!
        }

        return lists;
    }

    TreeNode find(TreeNode root, List<Integer> list) {
        if (root == null) return null;

        if(root.left == null && root.right == null) {
            list.add(root.val);
            return null; // !!!
        }

        root.left = find(root.left, list); // modify left leaf
        root.right = find(root.right, list); // modify right leaf

        return root;
    }
}