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.

2 4 3 5 R L R

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 past to 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"] ?

  1. Start at node 2: Stack = []

  2. Move "R": Add 2 to stack, move to node 4. Stack = [2]

  3. Move "R": Add 4 to stack, move to node 5. Stack = [2, 4]

  4. Move "U": Remove 4 from stack, go back to node 4. Stack = [2]

  5. Move "L": Add 4 to stack, move to node 3. Stack = [2, 4]

  6. 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.

Updated on: 2026-03-25T11:44:20+05:30

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements