Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //logic is simple,get root node first then left boundary then leafes then right boundary
- //left and right fun not printing root because we are passing it root->left and rppt->right
- //left and right fun not printing leaves we are printing data of only that nodes which have either root->left or root->right.
- def left_tra(root, ans):
- if root and (root.left or root.right): # skip leaf nodes
- ans.append(root.data)
- if root.left:
- left_tra(root.left, ans)
- else:
- left_tra(root.right, ans)
- def leaves(root, ans):
- if root is None:
- return
- if root.left is None and root.right is None:
- ans.append(root.data)
- leaves(root.left, ans)
- leaves(root.right, ans)
- def right_tra(root, ans):
- if root and (root.left or root.right): # skip leaf nodes
- if root.right:
- right_tra(root.right, ans)
- else:
- right_tra(root.left, ans)
- ans.append(root.data) # add after recursion (to reverse)
- class Solution:
- def boundaryTraversal(self, root):
- if not root:
- return []
- ans = [root.data]
- left_tra(root.left, ans)
- leaves(root.left, ans) #We have asked leaves two times because if tree has only one node,it will work,
- leaves(root.right,ans)
- right_tra(root.right, ans)
- return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement