Example:
Given binary Tree
1 / 2 3 /\ 4 5
Returns [4, 5, 3], [2], [1]
.
Explanation:
1. Removing the leaves [4, 5, 3]
would result in this tree:
1 / 2
2. Now removing the leaf [2]
would a result in this tree:
1
3. Now removing the leaf [1]
would result in the empty tree:
[]
Returns [4, 5, 3], [2], [1]
.
Solution:
Mark tree by level, if it was leave then mark as Level 0 and then add to the list<list<int>> by level.
/** Definition for a binary tree node. * public class TreeNode {* public int val, * public TreeNode left; public TreeNode right; * Public TreeNode (int x) {val = x;} }*/ Public classSolution { Publicilist<ilist<int>>findleaves (TreeNode root) {IList<IList<int>> result =Newlist<ilist<int>> (); Leaveslevel (root, result); returnresult; } Public intLeaveslevel (TreeNode root, ilist<ilist<int>>result) { if(root==NULL) { return-1; } intLeftlevel =Leaveslevel (root.left, result); intRightlevel =Leaveslevel (root.right, result); intLevel = Math.max (Leftlevel, Rightlevel) +1; if(result.) Count () <level+1) {result. ADD (Newlist<int>()); } Result[level]. ADD (Root.val); returnLevel ; }}
366. Find Leaves of Binary Tree C #