1. 程式人生 > >Leetcode 366. Find Leaves of Binary Tree

Leetcode 366. Find Leaves of Binary Tree

oot mov end res removing self. elf 一個 emp

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