Given A binary tree, collect a tree ' s nodes as if you were doing this:collect and remove all leaves, repeat until th E Tree is empty. example:given binary tree 1/ /span>2 3/ \ 4 5 Returns [ 4, 5, 3], [2], [1 1. Removing the leaves [4, 5, 3] would result in this tree : 1/2 2. Now removing the leaf [2] would result in this tree: 1 3. Now removing the leaf [14, 5, 3], [2], [1].
Better SOLUTION:HTTPS://DISCUSS.LEETCODE.COM/TOPIC/49194/10-LINES-SIMPLE-JAVA-SOLUTION-USING-RECURSION-WITH-EXPLANATION/2
For the question we need to take bottom-up approach. The key is to find the height of each node. The height of a node is the number of edges from the node to the deepest leaf.
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One PublicList<list<integer>>findleaves (TreeNode root) { Alist<list<integer>> res =NewArraylist<>(); - Helper (root, res); - returnRes; the } - - Public intHelper (TreeNode cur, list<list<integer>>Res) { - if(cur = =NULL)return-1; + intLevel = 1 +Math.max (Helper (Cur.left, res), helper (Cur.right, res)); - if(Res.size () <=Level ) +Res.add (NewArraylist<integer>()); A Res.get (Level). Add (cur.val); atCur.left = Cur.right =NULL; - returnLevel ; - } -}
First time solution:hashset+ DFS
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One PublicList<list<integer>>findleaves (TreeNode root) { Aarraylist<list<integer>> res =NewArraylist<list<integer>>(); - if(Root = =NULL)returnRes; -Hashset<treenode> visited =NewHashset<>(); the while(!visited.contains (Root)) { -Arraylist<integer> leaves =NewArraylist<integer>(); - helper (root, leaves, visited); -Res.add (NewArraylist<integer>(leaves)); + } - returnRes; + } A at Public voidHelper (TreeNode cur, arraylist<integer> leaves, hashset<treenode>visited) { - if((cur.left==NULL|| Visited.contains (Cur.left)) && (cur.right==NULL||visited.contains (cur.right))) { - Leaves.add (cur.val); - visited.add (cur); - return; - } in if(cur.left!=NULL&&!visited.contains (cur.left)) - Helper (Cur.left, leaves, visited); to if(cur.right!=NULL&&!visited.contains (cur.right)) + Helper (Cur.right, leaves, visited); - } the}
Leetcode:find Leaves of Binary Tree