码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 366. Find Leaves of Binary Tree

时间:2017-05-10 12:51:37      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:leetcode   解法   node   append   find   val   res   设置   blog   

Given a binary tree, collect a tree‘s nodes as if you were doing this: Collect and remove all leaves, repeat until the tree 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 result in this tree:

          1          

3. Now removing the leaf [1] would result in the empty tree:

          []         

Returns [4, 5, 3], [2], [1].

 

解法一: 一层一层的将所有的叶子拔掉,每次去掉一个叶子,就把这个叶子的val设置成‘#‘。

 1 class Solution(object):
 2     def findLeaves(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: List[List[int]]
 6         """
 7         ans = []
 8         if not root:
 9             return ans
10             
11         while root.val != #:
12             curL = []
13             self.removeCurLeaves(root, curL)
14             ans.append([x for x in curL])
15         return ans
16         
17         
18     def removeCurLeaves(self, node, res):
19         if (not node.left or node.left.val == #) and (not node.right or node.right.val == #):
20             res.append(node.val)
21             node.val = #
22             return 
23         if node.left and node.left.val != #:
24             self.removeCurLeaves(node.left, res)
25         if node.right and node.right.val != #:
26             self.removeCurLeaves(node.right, res)

 

Leetcode 366. Find Leaves of Binary Tree

标签:leetcode   解法   node   append   find   val   res   设置   blog   

原文地址:http://www.cnblogs.com/lettuan/p/6228553.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!