Advertisement
jinhuang1102

545. Boundary of Binary Tree

Nov 25th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. class Solution(object):
  2.     def dfs_leftmost(self, root, res):
  3.         if not root or not root.left and not root.right:
  4.             return
  5.        
  6.         res.append(root.val)
  7.         if root.left:
  8.             self.dfs_leftmost(root.left, res)
  9.         else:
  10.             self.dfs_leftmost(root.right, res)
  11.            
  12.     def dfs_leaves(self, root, res, exl_node):
  13.         if not root:
  14.             return
  15.        
  16.         self.dfs_leaves(root.left, res, exl_node)
  17.         if root != exl_node and not root.left and not root.right:
  18.             res.append(root.val)
  19.         self.dfs_leaves(root.right, res, exl_node)
  20.        
  21.     def dfs_rightmost(self, root, res):
  22.         if not root or not root.left and not root.right:
  23.             return
  24.        
  25.         if root.right:
  26.             self.dfs_rightmost(root.right, res)
  27.         else:
  28.             self.dfs_rightmost(root.left, res)
  29.         res.append(root.val)
  30.    
  31.    
  32.     def boundaryOfBinaryTree(self, root):
  33.         """
  34.        :type root: TreeNode
  35.        :rtype: List[int]
  36.        """
  37.         res = []
  38.         if not root:
  39.             return res
  40.         res.append(root.val)
  41.         self.dfs_leftmost(root.left, res)
  42.         self.dfs_leaves(root, res, root)
  43.         self.dfs_rightmost(root.right, res)
  44.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement