
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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
- Program to convert linked list to zig-zag binary tree in Python
- Program to fix a erroneous binary tree using Python
- Python Program to Sort using a Binary Search Tree
- Program to change the root of a binary tree using Python
- Program to convert level order binary tree traversal to linked list in Python
- Python program to convert a given binary tree to doubly linked list
- Program to invert a 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
- Program to find out the lowest common ancestor of a binary tree using Python
- Golang Program to traverse a given tree in Postorder Traversal (Recursive).
