Skip to main content

Sum of leaf node in BST using recursion in php

Sum of leaf nodes

Php program for Sum of leaf node in BST using recursion. Here more solutions.

<?php
// Php program for
// Sum of all leaf nodes of binary search tree
// Using recusion
class TreeNode
{
	public $data;
	public $left;
	public $right;
	public	function __construct($data)
	{
		$this->data = $data;
		$this->left = NULL;
		$this->right = NULL;
	}
}
class BinarySearchTree
{
	public $root;
	public	function __construct()
	{
		$this->root = NULL;
	}
	// insert a new node
	public	function addNode($data)
	{
		// Create a new node
		$node = new TreeNode($data);
		if ($this->root == NULL)
		{
			// When adds a first node in bst
			$this->root = $node;
		}
		else
		{
			$find = $this->root;
			// Add new node to proper position
			while ($find != NULL)
			{
				if ($find->data >= $data)
				{
					if ($find->left == NULL)
					{
						// When left child empty
						// So add new node here
						$find->left = $node;
						return;
					}
					else
					{
						// Otherwise
						// Visit left sub-tree
						$find = $find->left;
					}
				}
				else
				{
					if ($find->right == NULL)
					{
						// When right child empty
						// So add new node here
						$find->right = $node;
						return;
					}
					else
					{
						// Visit right sub-tree
						$find = $find->right;
					}
				}
			}
		}
	}
	// Sum of leaf nodes
	public	function leafNodeSum($node)
	{
		if ($node != NULL)
		{
			if ($node->left == NULL && $node->right == NULL)
			{
				// When node is leaf node
				return $node->data;
			}
			// Visit to left and right subtree
			return $this->leafNodeSum($node->left) + 
              $this->leafNodeSum($node->right);
		}
		return 0;
	}
	public static function main()
	{
		$tree = new BinarySearchTree();
		// Add nodes in binary search tree
		/*
		            5
		          /   \ 
		         /     \
		        3       9
		       / \     /  \
		      2   4   8    10
		             / 
		            6

		*/
		$tree->addNode(5);
		$tree->addNode(3);
		$tree->addNode(9);
		$tree->addNode(2);
		$tree->addNode(4);
		$tree->addNode(8);
		$tree->addNode(10);
		$tree->addNode(6);
		// Test
		printf("%d", $tree->leafNodeSum($tree->root));
	}
}
BinarySearchTree::main();

Output

22




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