Binary Tree Preorder Traversal: A Recursive Approach

Binary Tree Preorder Traversal: A Recursive Approach

Problem Statement

Given a binary tree, return its inorder traversal. The inorder traversal of a binary tree is a sequence of nodes visited in the following order: left subtree, root, and right subtree.

Example

Input: [1, null, 2, 3]
Output: [1, 3, 2]

Approach

The inorder traversal can be achieved using a recursive approach. This approach involves processing the left subtree, then the root, and finally the right subtree.

Java Implementation

// Definition for a binary tree node.
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    List<Integer> list = new ArrayList<>();

    public List<Integer> inorderTraversal(TreeNode root) {
        if (root != null) {
            inorderTraversal(root.left);
            list.add(root.val);
            inorderTraversal(root.right);
        }
        return list;
    }
}

Python Implementation

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        if root is not None:
            res = res + self.inorderTraversal(root.left)
            res = res + [root.val]
            res = res + self.inorderTraversal(root.right)
        return res

Comparison

This problem involves a binary tree preorder traversal, which can be solved using a recursive approach. The recursive approach involves processing the left subtree, then the root, and finally the right subtree. The Java and Python implementations demonstrate the recursive approach to inorder traversal.

Key Takeaways

  • The inorder traversal of a binary tree is a sequence of nodes visited in the following order: left subtree, root, and right subtree.
  • The recursive approach involves processing the left subtree, then the root, and finally the right subtree.
  • The Java and Python implementations demonstrate the recursive approach to inorder traversal.

Join the Conversation

Share your thoughts on binary tree preorder traversal and recursive approaches in the comments below. Join the conversation on Tencent Cloud’s media-sharing plan and share your own experiences with binary tree traversal.