
Sponsored
Sponsored
This approach uses recursion to traverse the binary tree. Inorder traversal involves visiting the left subtree, the root node, and then the right subtree. The base case for the recursion is to return if the current node is null.
Time Complexity: O(n), where n is the number of nodes in the binary tree.
Space Complexity: O(n) due to the recursion stack.
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def inorderTraversal(self, root):
9 result = []
10 self.inorder(root, result)
11 return result
12
13 def inorder(self, root, result):
14 if root is not None:
15 self.inorder(root.left, result)
16 result.append(root.val)
17 self.inorder(root.right, result)The Python solution uses a class-based approach with two methods. The inorderTraversal method initializes the result list and invokes a recursive inorder method to populate the list with the node values following an inorder sequence.
In this approach, we use a stack to perform an iterative inorder traversal. The stack is utilized to track the nodes to be visited. This method mimics the recursive behavior by explicitly using a stack to push left children until reaching a null entry, then processes the nodes and explores the right subtrees.
Time Complexity: O(n)
Space Complexity: O(n)
1
The C implementation employs a manual stack data structure to facilitate the iterative traversal. Nodes are pushed onto the stack until null is reached, allowing us to backtrack, visit the node, and repeat the process for the right subtree.