Algorithm Steps
- Start with the
root
node of the binary tree. - If the tree is empty, return an empty result.
- Recursively perform inorder traversal on the left subtree.
- Visit the current node and record its value.
- Recursively perform inorder traversal on the right subtree.
- Combine the results to produce the final inorder sequence.
Inorder Traversal of a Binary Tree using Recursion - Code Examples Code
Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorderTraversal(root):
if not root:
return []
return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right)
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
print(inorderTraversal(root))