jinhuang1102

366. Find Leaves of Binary Tree

Mar 17th, 2019
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. """
  2. 366. Find Leaves of Binary Tree
  3. 用的是层层玻璃的方法, 没经过一次while loop 所有的叶节点,都会笔记录下来,并移除掉
  4. """
  5. class Solution(object):
  6.     def remove(self, node, ls):
  7.         if not node:       
  8.             return None
  9.        
  10.         if not node.left and not node.right: #如果是叶节点,append到ls中,并且返回 None
  11.             ls.append(node.val)
  12.             return None
  13.        
  14.         node.left = self.remove(node.left, ls)  # 这一步其实是在移除叶节点
  15.         node.right = self.remove(node.right, ls)
  16.        
  17.         return node
  18.    
  19.    
  20.     def findLeaves(self, root):
  21.         """
  22.        :type root: TreeNode
  23.        :rtype: List[List[int]]
  24.        """
  25.         res = []
  26.        
  27.         while root:
  28.             leaves = []             # 记录每一次循环的叶节点
  29.             root = self.remove(root, leaves)
  30.             res.append(leaves)
  31.            
  32.         return res
Advertisement
Add Comment
Please, Sign In to add comment