Binary Tree Traversals in PHP

Lesson Overview

Welcome to an exploration through the intricate paths of binary structures. In this lesson, we will delve into the concept of Binary Tree Traversals. A Binary Tree is a structured format in which each node has at most two children, known as the left child and the right child. Navigating through this structure is referred to as traversal, where each node is visited in a particular sequence. PHP, with its robust object-oriented capabilities, provides an efficient framework to accomplish this task seamlessly.

Binary Tree Definition

Before venturing deeper into traversal techniques, let's outline a basic framework for a binary tree node in PHP. Each node will hold a value, along with references to its left and right children, respectively.

Here’s how you can define a basic binary tree node class in PHP:

class TreeNode {
    public $value;
    public $left;
    public $right;

    public function __construct($value, $left = null, $right = null) {
        $this->value = $value;
        $this->left = $left;
        $this->right = $right;
    }
}

This TreeNode class initializes a node with a specified value and optional left and right children, defaulting to null if not provided. This framework is foundational for implementing different methods of binary tree traversal.

Quick Example

Traversing a binary tree can be approached primarily in three ways: Inorder (Left, Root, Right), Preorder (Root, Left, Right), and Postorder (Left, Right, Root). For instance, a recursive Inorder traversal would first recursively explore the left subtree, visit the root, and finally traverse the right subtree. Through this approach, the entirety of the binary structure can be examined.

Here is an example in PHP:

class BinaryTreeTraversal {

    public static function inorderTraversal($root) {
        $result = [];
        self::inorderHelper($root, $result);
        return $result;
    }

    private static function inorderHelper($node, &$result) {
        if ($node == null) {
            return;
        }
        self::inorderHelper($node->left, $result);
        $result[] = $node->value;
        self::inorderHelper($node->right, $result);
    }
}

// Example usage:
$root = new TreeNode(1, null, new TreeNode(2, new TreeNode(3), null));
print_r(BinaryTreeTraversal::inorderTraversal($root));  // Output: [1, 3, 2]
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal