Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find if given vertical level of binary tree is sorted or not in Python
In binary tree problems, we often need to analyze nodes at specific vertical levels. A vertical level represents all nodes that are at the same horizontal distance from the root. This problem asks us to check if nodes at a given vertical level are sorted in ascending order.
Understanding Vertical Levels
In a binary tree, vertical levels are determined by horizontal distance from the root ?
Root node is at vertical level 0
Left child is at (parent's level - 1)
Right child is at (parent's level + 1)
Algorithm Approach
We use level-order traversal with a queue to track each node's vertical level. For the target level, we check if values appear in sorted order ?
Implementation
from collections import deque
class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
def is_vertical_level_sorted(root, target_level):
if not root:
return True
queue = deque([(root, 0)]) # (node, vertical_level)
previous_value = float('-inf')
while queue:
node, level = queue.popleft()
# Check if current node is at target level
if level == target_level:
if previous_value <= node.val:
previous_value = node.val
else:
return False
# Add children to queue with updated levels
if node.left:
queue.append((node.left, level - 1))
if node.right:
queue.append((node.right, level + 1))
return True
# Create the binary tree from the example
root = TreeNode(2)
root.left = TreeNode(3)
root.right = TreeNode(6)
root.left.left = TreeNode(8)
root.left.right = TreeNode(5)
root.left.right.left = TreeNode(7)
# Test with different vertical levels
print("Level -1 sorted:", is_vertical_level_sorted(root, -1))
print("Level 0 sorted:", is_vertical_level_sorted(root, 0))
print("Level 1 sorted:", is_vertical_level_sorted(root, 1))
The output of the above code is ?
Level -1 sorted: True Level 0 sorted: True Level 1 sorted: True
How It Works
The algorithm processes nodes level by level using BFS. When it encounters a node at the target vertical level, it compares the value with the previous value from the same level ?
Initialize: Queue with root at level 0, previous_value as negative infinity
Process: For each node, check if it's at target level
Validate: If at target level, ensure value ? previous value
Expand: Add left child (level-1) and right child (level+1) to queue
Testing Different Cases
# Test with unsorted vertical level
root2 = TreeNode(1)
root2.left = TreeNode(5) # Level -1
root2.right = TreeNode(3) # Level +1
root2.left.left = TreeNode(2) # Level -2
root2.left.right = TreeNode(4) # Level 0
print("Unsorted case - Level -1:", is_vertical_level_sorted(root2, -1))
# Create nodes at level -1: [5] - this should be True (single element)
root3 = TreeNode(1)
root3.left = TreeNode(3)
root3.left.left = TreeNode(8) # Level -2
root3.left.right = TreeNode(2) # Level 0
print("Single element - Level -1:", is_vertical_level_sorted(root3, -1))
Unsorted case - Level -1: True Single element - Level -1: True
Time and Space Complexity
Time Complexity: O(n) where n is the number of nodes
Space Complexity: O(w) where w is the maximum width of the tree
Conclusion
This solution uses BFS to traverse nodes level by level, checking if values at the target vertical level maintain sorted order. The algorithm efficiently handles overlapping nodes by processing them in the order they appear during traversal.
