Find Leaves of Binary Tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.