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 traverse binary tree using list of directions in Python
Suppose we have a binary tree and a list of strings moves consisting of "R" (Right), "L" (Left) and "U" (Up). Starting from root, we have to traverse the tree by performing each move in moves where: "R" indicates traverse to the right child, "L" indicates traverse to the left child, and "U" indicates traverse to its parent.
For the tree above with moves ["R","R","U","L"], the output will be 3.
Algorithm
To solve this problem, we will follow these steps ?
Create a stack
pastto keep track of visited nodes-
For each move in moves, do ?
Add current root to the stack
If move is "L", traverse to left child
If move is "R", traverse to right child
If move is "U", go back to parent using the stack
Return the value of the final node
Example
class TreeNode:
def __init__(self, data, left=None, right=None):
self.val = data
self.left = left
self.right = right
class Solution:
def solve(self, root, moves):
past = []
for move in moves:
past.append(root)
if move == "L":
root = root.left
elif move == "R":
root = root.right
else: # move == "U"
past.pop() # Remove current node
root = past.pop() # Go to parent
return root.val
# Create the binary tree
root = TreeNode(2)
root.right = TreeNode(4)
root.right.left = TreeNode(3)
root.right.right = TreeNode(5)
# Define moves and solve
ob = Solution()
traverse = ["R", "R", "U", "L"]
result = ob.solve(root, traverse)
print(result)
3
How It Works
Let's trace through the moves ["R", "R", "U", "L"] ?
Start at node 2: Stack = []
Move "R": Add 2 to stack, move to node 4. Stack = [2]
Move "R": Add 4 to stack, move to node 5. Stack = [2, 4]
Move "U": Remove 4 from stack, go back to node 4. Stack = [2]
Move "L": Add 4 to stack, move to node 3. Stack = [2, 4]
Return: Current node value is 3
Conclusion
This solution uses a stack to track the path and enables upward traversal in a binary tree. The time complexity is O(n) where n is the number of moves, and space complexity is O(h) where h is the height of the tree.
