Advertisement
imashutosh51

Boundary Traversal of binary tree

Aug 4th, 2022 (edited)
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. //logic is simple,get root node first then left boundary then leafes then right boundary
  2. //left and right fun not printing root because we are passing it root->left and rppt->right
  3. //left and right fun not printing leaves we are printing data of only that nodes which have either root->left or root->right.
  4.  
  5. def left_tra(root, ans):
  6.     if root and (root.left or root.right):  # skip leaf nodes
  7.         ans.append(root.data)
  8.         if root.left:
  9.             left_tra(root.left, ans)
  10.         else:
  11.             left_tra(root.right, ans)
  12.  
  13. def leaves(root, ans):
  14.     if root is None:
  15.         return
  16.     if root.left is None and root.right is None:
  17.         ans.append(root.data)
  18.     leaves(root.left, ans)
  19.     leaves(root.right, ans)
  20.  
  21. def right_tra(root, ans):
  22.     if root and (root.left or root.right):  # skip leaf nodes
  23.         if root.right:
  24.             right_tra(root.right, ans)
  25.         else:
  26.             right_tra(root.left, ans)
  27.         ans.append(root.data)  # add after recursion (to reverse)
  28.  
  29. class Solution:
  30.     def boundaryTraversal(self, root):
  31.         if not root:
  32.             return []
  33.         ans = [root.data]
  34.  
  35.         left_tra(root.left, ans)
  36.         leaves(root.left, ans) #We have asked leaves two times because if tree has only one node,it will work,
  37.         leaves(root.right,ans)
  38.         right_tra(root.right, ans)
  39.  
  40.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement