Skip to main content

Detect leaf nodes of threaded BST in php

Print leaf node in Threaded BST

Php program for Detect leaf nodes in threaded BST. Here more solutions.

<?php
// Php program for
// Print leaf node in Threaded BST
class TreeNode
{
	public $data;
	public $left;
	public $right;
	public	function __construct($data, $left, $right)
	{
		$this->data = $data;
		$this->left = $left;
		$this->right = $right;
	}
}
class BinarySearchTree
{
	public $root;
	public	function __construct()
	{
		$this->root = NULL;
	}
	// Added node in Threaded BST
	function addNode($node, $x, $y, $data)
	{
		if ($node != NULL)
		{
			if ($node->data >= $data)
			{
				if ($node->left == $x)
				{
					$node->left = new TreeNode($data, $x, $node);
				}
				else
				{
					$node->left = $this->addNode(
                      $node->left, 
                      $x, 
                      $node, 
                      $data);
				}
			}
			else if ($node->data < $data)
			{
				if ($node->right == $y)
				{
					$node->right = new TreeNode(
                      $data, 
                      $node, 
                      $y);
				}
				else
				{
					$node->right = $this->addNode(
                      $node->right, 
                      $node, 
                      $y, 
                      $data);
				}
			}
			return $node;
		}
		else
		{
			return new TreeNode($data, $x, $y);
		}
	}
	// Adding a new node in binary search tree
	public	function add($data)
	{
		$this->root = $this->addNode($this->root, NULL, NULL, $data);
	}
	// Print all leaf node in Threaded BST
	public	function leafNode($node, $x, $y)
	{
		if ($node != NULL)
		{
			if ($node->left == $x && $node->right == $y)
			{
				// This is a leaf node Then print
				echo "  ".($node->data);
				return;
			}
			if ($node->left != $x)
			{
				// Visit left child
				$this->leafNode($node->left, $x, $node);
			}
			if ($node->right != $y)
			{
				// Visit right child
				$this->leafNode($node->right, $node, $y);
			}
		}
	}
	public static function main()
	{
		$tree = new BinarySearchTree();
		// Add nodes in binary search tree
		/*
		            5
		           / \
		          /   \
		         /     \
		        3       9
		       / \     / \
		      1   4   8   11
		     / \     /      \
		   -3   2   7        12
		        
		*/
		$tree->add(5);
		$tree->add(3);
		$tree->add(9);
		$tree->add(1);
		$tree->add(4);
		$tree->add(8);
		$tree->add(11);
		$tree->add(-3);
		$tree->add(2);
		$tree->add(7);
		$tree->add(12);
		// Test
		$tree->leafNode($tree->root, NULL, NULL);
	}
}
BinarySearchTree::main();

Output

  -3  2  4  7  12




Comment

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