We can print the boundary of a binary tree. Here’s a step-by-step approach to solving this:
A Binary Tree boundary is defined as the perimeter of the binary tree. Starting from the root, boundary traversal should be done anti-clockwise starting from the root. Boundary includes left boundary, leaves, and right boundary.
To print the boundary, we divide the problem in three parts:
1. Print the left boundary in top-down manner.
2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts:
2.1 Print all leaf nodes of the left sub-tree from left to right.
2.2 Print all leaf nodes of the right subtree from left to right.
3. Print the right boundary in bottom-up manner.
We need to take care of one thing that nodes are not printed again. For example, the left most node is also the leaf node of the tree.
Here is the pseudocode to implement the above approach:
# A function to print all left boundary nodes, except a leaf node.
def printLeftBoundary(node):
if node:
if node.left:
# to ensure top-down order, print the node
# before calling itself for left subtree
print(node.data)
printLeftBoundary(node.left)
elif node.right:
print(node.data)
printLeftBoundary(node.right)
# do nothing if it is a leaf node, this way we avoid
# duplicates in output
# A function to print all right boundary nodes, except a leaf node
def printRightBoundary(node):
if node:
if node.right:
# to ensure bottom-up order, first call for right
# subtree, then print this node
printRightBoundary(node.right)
print(node.data)
elif node.left:
printRightBoundary(node.left)
print(node.data)
# A function to print all leaf nodes
def printLeaves(node):
if node:
printLeaves(node.left)
# print it if it is a leaf node
if node.left is None and node.right is None:
print(node.data)
printLeaves(node.right)
# A function to do boundary traversal of a given binary tree
def printBoundary(node):
if node:
print(node.data)
# Print the left boundary in top-down manner
printLeftBoundary(node.left)
# Print all leaf nodes
printLeaves(node.left)
printLeaves(node.right)
# Print the right boundary in bottom-up manner
printRightBoundary(node.right)
Note, this technique works best with binary trees, not binary search trees (BSTs). In binary search trees, data is organized in a specific way that can be leveraged for more efficient solutions. However, with binary trees, data is relatively unorganized and requires a more comprehensive traversal and printing technique.