imashutosh51

Tree Bounday Traversal

Aug 4th, 2022 (edited)
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. """
  2. Boundary traversal is done in anti-clockwise order: root -> left boundary -> all leaves -> right boundary.
  3. Left and right boundary functions skip leaf nodes to avoid duplicates (leaves are collected separately).
  4. We call left_tra(root.left) and right_tra(root.right) so root is not repeated.
  5. Right boundary is added after recursion so it automatically comes in reverse order.
  6. """
  7. def left_tra(root, ans):  
  8.     if root and (root.left or root.right): # skip leaf nodes
  9.         ans.append(root.data)
  10.         if root.left:
  11.             left_tra(root.left, ans)
  12.         else:
  13.             left_tra(root.right, ans)
  14.  
  15. def leaves(root, ans):
  16.     if not root:
  17.         return
  18.     if not root.left and not root.right: # leaf node
  19.         ans.append(root.data)
  20.         return
  21.    
  22.     leaves(root.left, ans)
  23.     leaves(root.right, ans)
  24.  
  25.  
  26. def right_tra(root, ans):
  27.     if root and (root.left or root.right): # skip leaf nodes
  28.         if root.right:
  29.             right_tra(root.right, ans)
  30.         else:
  31.             right_tra(root.left, ans)
  32.         ans.append(root.data) # add after recursion for reverse order
  33.  
  34.  
  35. class Solution:
  36.     def boundaryTraversal(self, root):
  37.         if not root:
  38.             return []
  39.         ans = []
  40.         if root.left or root.right: # add root only if not leaf
  41.             ans.append(root.data)
  42.        
  43.         left_tra(root.left, ans) # left boundary
  44.         leaves(root, ans) # all leaves
  45.         right_tra(root.right, ans) # right boundary in reverse
  46.         return ans
Advertisement
Add Comment
Please, Sign In to add comment