when we do a left traversal from root to bottom (when we look at tree from the left) excluding leaf nodes + leaf nodes + right traversal (from the bottom excluding leaf node to root)
btw be careful to also look at other side for left and right traversal. What i mean is not if we are doing left traversal, we shouldnt just dfs onto left nodes only. If there are no left nodes, we have to traverse to its right node. same for right traversal.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def boundaryOfBinaryTree(root):
if not root:
return []
result = [root.val]
# 1. Left boundary (root to leaf, exclude leaf)
def leftBoundary(node):
if not node:
return
if not node.left and not node.right:
return
result.append(node.val)
if node.left:
leftBoundary(node.left)
else:
leftBoundary(node.right)
# 2. Leaves (left to right)
def leaves(node):
if not node:
return
if not node.left and not node.right:
result.append(node.val)
return
leaves(node.left)
leaves(node.right)
# 3. Right boundary (leaf to root, exclude leaf)
def rightBoundary(node):
if not node:
return
if not node.left and not node.right:
return
if node.right:
rightBoundary(node.right)
else: # ✅ "else", not "if"
rightBoundary(node.left)
result.append(node.val)
leftBoundary(root.left)
leaves(root)
rightBoundary(root.right)
return result
# Test tree:
# 1
# / \
# 2 3
# \
# 5
# \
# 7
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(5)
root.left.right.right = TreeNode(7)
result = boundaryOfBinaryTree(root)
print("Boundary:", result)
# Expected: [1, 2, 5, 7, 3]
n time and space