Inorder traversal of binary tree with recursion in php

Php program for Inorder traversal of binary tree with recursion. Here problem description and explanation.

<?php
/* 
  Php Program for
  inorder tree traversal of a Binary Tree
  using recursion
*/
// Binary Tree Node
class TreeNode
{
	public $data;
	public $left;
	public $right;
	public	function __construct($data)
	{
		// Set node value
		$this->data = $data;
		$this->left = NULL;
		$this->right = NULL;
	}
}
class BinaryTree
{
	public $root;
	public	function __construct()
	{
		$this->root = NULL;
	}
	// Display Inorder view of binary tree
	public	function inorder($node)
	{
		if ($node != NULL)
		{
			// Visit left subtree
			$this->inorder($node->left);
			//Print node value
			printf("%d  ",$node->data);
			// Visit right subtree
			$this->inorder($node->right);
		}
	}
	public static
	function main($args)
	{
		// Create new tree
		$tree = new BinaryTree();
		/*
		    Make A Binary Tree
		    ----------------
		        15
		       /  \
		      24   54
		     /    /  \
		    35   62   13
		*/
		// Add tree TreeNode
		$tree->root = new TreeNode(15);
		$tree->root->left = new TreeNode(24);
		$tree->root->right = new TreeNode(54);
		$tree->root->right->right = new TreeNode(13);
		$tree->root->right->left = new TreeNode(62);
		$tree->root->left->left = new TreeNode(35);
		// Display Tree Node
		$tree->inorder($tree->root);
	}
}
BinaryTree::main(array());

Output

35  24  15  62  54  13


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved