Complete the code to check if a node is a leaf node.
def is_leaf(node): return node.left is None and node.[1] is None
The function checks if both left and right children are None, meaning the node is a leaf.
Complete the code to traverse the left boundary excluding leaf nodes.
def add_left_boundary(root, res): curr = root.left while curr: if not is_leaf(curr): res.append(curr.data) curr = curr.[1]
We move down the left boundary by following the left child pointers.
Fix the error in the code to add leaf nodes in left-to-right order.
def add_leaves(root, res): if is_leaf(root): res.append(root.data) return if root.left: add_leaves(root.[1], res) if root.right: add_leaves(root.right, res)
To traverse leaves left to right, recurse first on the left child, then on the right child.
Fill both blanks to traverse the right boundary excluding leaf nodes in bottom-up order.
def add_right_boundary(root, res): curr = root.[1] temp = [] while curr: if not is_leaf(curr): temp.append(curr.data) curr = curr.[2] for i in reversed(temp): res.append(i)
Start from the right child of root and move down the right boundary by following the right child pointers, collecting nodes to add in reverse order.
Fill the blanks to complete the boundary traversal function.
def boundary_traversal(root): if root is None: return [] res = [root.data] add_left_boundary(root, res) add_leaves(root.[1], res) add_leaves(root.[2], res) add_right_boundary(root, res) return res
Leaves are collected from left subtree then right subtree. Left boundary and right boundary are added separately.
