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
Selected Reading
Program to check whether inorder sequence of a tree is palindrome or not in Python
Suppose we have a binary tree where each node contains a digit from 0-9, we have to check whether its in-order traversal is palindrome or not.
So, if the input is like
then the output will be True, as its inorder traversal is [2, 6, 10, 6, 2].
Algorithm
To solve this, we will follow these steps ?
- If root is null, return True
- Create a stack and initialize current node as root
- Create an empty list to store inorder traversal
- Perform iterative inorder traversal using stack
- Check if the inorder list is equal to its reverse
Implementation
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):
if not root:
return True
stack = []
curr = root
inorder = []
# Iterative inorder traversal
while stack or curr:
while curr:
stack.append(curr)
curr = curr.left
node = stack.pop()
inorder.append(node.val)
curr = node.right
# Check if inorder traversal is palindrome
return inorder == inorder[::-1]
# Test the solution
ob = Solution()
root = TreeNode(6)
root.left = TreeNode(2)
root.right = TreeNode(6)
root.right.left = TreeNode(10)
root.right.right = TreeNode(2)
print(ob.solve(root))
True
How It Works
The algorithm performs an iterative inorder traversal using a stack:
- Left traversal: Keep going left and push nodes onto the stack
- Process node: When no more left nodes, pop from stack and add value to inorder list
- Right traversal: Move to the right child and repeat
- Palindrome check: Compare the inorder list with its reverse using slicing
Alternative Recursive Approach
class Solution:
def solve_recursive(self, root):
def inorder(node, result):
if node:
inorder(node.left, result)
result.append(node.val)
inorder(node.right, result)
if not root:
return True
inorder_list = []
inorder(root, inorder_list)
return inorder_list == inorder_list[::-1]
# Test recursive approach
ob = Solution()
root = TreeNode(6)
root.left = TreeNode(2)
root.right = TreeNode(6)
root.right.left = TreeNode(10)
root.right.right = TreeNode(2)
print(ob.solve_recursive(root))
True
Conclusion
Both iterative and recursive approaches work effectively to check if a binary tree's inorder traversal forms a palindrome. The iterative method uses O(h) space for the stack, while the recursive approach uses O(h) space for the call stack, where h is the height of the tree.
Advertisements
