Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps until the tree was empty.
Example:
Given binary Tree
1
/ \
2 3
/ \
4 5
Returns [4, 5, 3], [2], [1].
Explanation:
1. Remove the leaves [4, 5, 3] from the tree
1
/
2
2. Remove the leaf [2] from the tree
1
3. Remove the leaf [1] from the tree
[]
Returns [4, 5, 3], [2], [1].
The focus of this topic is to prune the tree, and we can use X = Change (x) in the recursive function. For example, Root.left = Removeleaves (root.left, result); Root.right = removeleaves (root.right, result) so that the null value returned by the underlying inline function can be assigned to the root.left/right of the upper call function. So the return type of the recursive function should naturally be set to TreeNode
1 Public classSolution {2 PrivateTreeNode removeleaves (TreeNode root, list<integer>result)3 {4 if(root==NULL)return NULL;5 if(Root.left = =NULL) && (root.right==NULL)){6 Result.add (root.val);7 return NULL;8 }9 TenRoot.left =removeleaves (root.left, result); OneRoot.right =removeleaves (root.right, result); A - returnRoot; - the } - - PublicList<list<integer>>findleaves (TreeNode root) { -list<list<integer>> res =NewArraylist<list<integer>>(); + if(root==NULL)returnRes; - while(root!=NULL){ +List<integer> leaves =NewArraylist<integer>(); ARoot =removeleaves (root, leaves); at Res.add (leaves); - } - - returnRes; - } -}
1
3. Remove the leaf [1] from the tree
[]
Returns [4, 5, 3], [2], [1].
Find Leaves of binary tree Find leaf nodes of two forks