Inorder Traversal of a Binary Tree using Recursion

Visualization

Algorithm Steps

  1. Start with the root node of the binary tree.
  2. If the tree is empty, return an empty result.
  3. Recursively perform inorder traversal on the left subtree.
  4. Visit the current node and record its value.
  5. Recursively perform inorder traversal on the right subtree.
  6. 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))