- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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. "U" indicates traverse to its parent.

So, if the input is like

["R","R","U","L"], then the output will be 3

To solve this, we will follow these steps −

past := a new list

for each move in moves, do

insert root at the end of past

if move is same as "L", then

root := left of root

otherwise when move is same as "R", then

root := right of root

otherwise,

delete last element from past

root := last element from past and delete it from past

return value of root

Let us see the following implementation to get better understanding −

## 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: past.pop() root = past.pop() return root.val ob = Solution() root = TreeNode(2) root.right = TreeNode(4) root.right.left = TreeNode(3) root.right.right = TreeNode(5) traverse = ["R","R","U","L"] print(ob.solve(root, traverse))

## Input

root = TreeNode(2) root.right = TreeNode(4) root.right.left = TreeNode(3) root.right.right = TreeNode(5) ["R","R","U","L"]

## Output

3

- Related Questions & Answers
- Program to traverse binary tree level wise in alternating way in Python
- Python Program to Implement Binary Tree using Linked List
- Golang Program to traverse a given binary tree in Preorder Traversal (Recursive)
- Program to create linked list to binary search tree in Python
- Python Program to Sort using a Binary Search Tree
- Program to fix a erroneous binary tree using Python
- Program to change the root of a binary tree using Python
- Program to convert linked list to zig-zag binary tree in Python
- Python program to convert a given binary tree to doubly linked list
- Program to convert level order binary tree traversal to linked list in Python
- Program to invert a binary tree in Python
- Changing Directions in Python
- Diameter of Binary Tree in Python
- Python Program for Depth First Binary Tree Search using Recursion
- Program to find top view of a binary tree in Python