首页 > 代码库 > Leetcode 366. Find Leaves of Binary Tree
Leetcode 366. Find Leaves of Binary Tree
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。