Given a binary tree, collect a tree ' s nodes as if you were doing this:collect and remove all leaves, repeat until the Tre E is empty.
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]
.
A very interesting problem, the main step is to remove the leaf node, and then return the results. In fact, this question is the height of the two-fork tree node. The lowest first output, the same height of a piece of output. A slightly modified recursive ball binary tree height method can be, at the same time can be determined according to the height of the place to add results. Space complexity O (LOGN), time complexity bit O (n), each node needs to be processed once. The code is as follows:
classsolution (object):deffindleaves (self, root):""": Type Root:treenode:rtype:list[list[int]]""" if notRoot:return[] Res=[] Self.dfs (Root, res)returnResdefDfs (self, root, res):if notRoot:return-1 Left=Self.dfs (Root.left, res) right=Self.dfs (Root.right, res) level= Max (left, right) + 1ifLen (res) = =level:res.append ([root.val])Else: Res[level].append (root.val) Root.left= Root.right =NonereturnLevel
Find Leaves of Binary Tree