@@ -0,0 +1,1821 @@
+package com.freetymekiyan.algorithms.level.medium;%0A%0Aimport com.freetymekiyan.algorithms.utils.Utils.TreeNode;%0A%0Aimport java.util.ArrayList;%0Aimport java.util.List;%0A%0A/**%0A * Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until%0A * the tree is empty.%0A * %3Cp%3E%0A * Example:%0A * Given binary tree%0A * 1%0A * / %5C%0A * 2   3%0A * / %5C%0A * 4   5%0A * Returns %5B4, 5, 3%5D, %5B2%5D, %5B1%5D.%0A * %3Cp%3E%0A * Explanation:%0A * 1. Removing the leaves %5B4, 5, 3%5D would result in this tree:%0A * %3Cp%3E%0A * 1%0A * /%0A * 2%0A * 2. Now removing the leaf %5B2%5D would result in this tree:%0A * %3Cp%3E%0A * 1%0A * 3. Now removing the leaf %5B1%5D would result in the empty tree:%0A * %3Cp%3E%0A * %5B%5D%0A * Returns %5B4, 5, 3%5D, %5B2%5D, %5B1%5D.%0A * %3Cp%3E%0A * Company Tags: LinkedIn%0A * Tags: Tree, Depth-first Search%0A */%0Apublic class FindLeavesOfBinaryTree %7B%0A%0A    /**%0A     * Tree, DFS(Backtracking).%0A     * Make use of one property of tree node, its height.%0A     * Height is the number of edges from the node to the deepest leaf.%0A     * So leaf node will have height 0.%0A     * This problem is just aggregating all nodes with same height into a list.%0A     */%0A    public List%3CList%3CInteger%3E%3E findLeaves(TreeNode root) %7B%0A        List%3CList%3CInteger%3E%3E res = new ArrayList%3C%3E();%0A        height(root, res);%0A        return res;%0A    %7D%0A%0A    /**%0A     * Return the height of a node.%0A     * height(node) = 1 + max(height(node.left), height(node.right))%0A     */%0A    private int height(TreeNode node, List%3CList%3CInteger%3E%3E res) %7B%0A        if (null == node) return -1;%0A        int level = 1 + Math.max(height(node.left, res), height(node.right, res));%0A        if (res.size() == level) %7B // Current level exceeds result list size%0A            res.add(new ArrayList%3C%3E());%0A        %7D%0A        res.get(level).add(node.val);%0A        // root.left = root.right = null;%0A        return level;%0A    %7D%0A%7D%0A

add 366 Find Leaves of Binary Tree