How do you print a binary tree in vertical order in a long answer?
- User
How do you print a binary tree in vertical order in a long answer?
- Assistant
How do you print a binary tree in vertical order in a long answer?
To print a binary tree in vertical order, we need to perform a vertical traversal of the tree.
One way to achieve this is by using a depth-first search (DFS) approach along with a hash map to store the node positions based on their vertical levels. We can follow the steps below:
Define a helper function to perform the DFS traversal:
Perform the DFS traversal starting from the root node:
Sort the hash map based on the horizontal positions.
Iterate over the sorted hash map and print the node values for each horizontal position.
Here's a Python implementation that demonstrates the above steps:
# Binary tree node definition
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def printVerticalOrder(root):
# Helper function for DFS traversal
def dfs(node, horizontalPos, hashMap):
# Base case
if node is None:
return
# Update the hash map with the node value
if horizontalPos in hashMap:
hashMap[horizontalPos].append(node.val)
else:
hashMap[horizontalPos] = [node.val]
# Recursive calls for left and right subtrees
dfs(node.left, horizontalPos - 1, hashMap)
dfs(node.right, horizontalPos + 1, hashMap)
# DFS traversal
hashMap = {}
dfs(root, 0, hashMap)
# Sort the hash map based on horizontal positions
sortedKeys = sorted(hashMap.keys())
# Print the node values for each horizontal position
for key in sortedKeys:
print(hashMap[key])
# Usage example:
# Create a binary tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
# Print the binary tree in vertical order
printVerticalOrder(root)
Running the above code will give the output:
[4]
[2]
[1, 5, 6]
[3]
[7]
The above output represents the vertical order nodes of the binary tree. The nodes [4], [2], [1, 5, 6], [3], and [7] are ordered vertically from left to right.
Not yet included in a published release.