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
Program to find leftmost deepest node of a tree in Python
In a binary tree, we often need to find the leftmost deepest node. This means finding the node at the maximum depth, and if multiple nodes exist at that depth, we return the leftmost one.
So, if the input is like
Then the output will be 4 as both 4 and 7 are at the deepest level, but 4 is the leftmost.
Algorithm
We use level-order traversal (BFS) to process nodes level by level ?
Initialize a queue with the root node
Track the leftmost node value at each level
For each level, the first node processed is the leftmost
The final leftmost value will be from the deepest level
Implementation
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
class Solution:
def solve(self, root):
if not root:
return None
queue = [root]
leftmost_value = root.val
while len(queue) > 0:
level_size = len(queue)
# Process all nodes at current level
for i in range(level_size):
current = queue.pop(0)
# First node in level is leftmost
if i == 0:
leftmost_value = current.val
# Add children for next level
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
return leftmost_value
# Create the tree from the example
ob = Solution()
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
print("Leftmost deepest node:", ob.solve(root))
Leftmost deepest node: 4
How It Works
The algorithm processes the tree level by level. At each level, we track the leftmost node (first node processed). When we finish traversing all levels, the leftmost_value contains the value of the leftmost node at the deepest level.
The time complexity is O(n) where n is the number of nodes, and space complexity is O(w) where w is the maximum width of the tree.
Conclusion
Level-order traversal efficiently finds the leftmost deepest node by processing nodes level by level. The first node at each level is always the leftmost, ensuring we get the correct result when multiple nodes exist at maximum depth.
