Skip to main content

Sum of all the grandchild nodes of binary tree in php

Sum of all nodes in binary tree whose grandparents exists

Php program for Sum of all the grandchild nodes of binary tree. Here mentioned other language solution.

<?php
/*
    Php program for
    Sum of nodes in binary tree whose grandparents exists
*/
// 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;
	}
	public	function preOrder($node)
	{
		if ($node != NULL)
		{
			// Print node value
			echo "  ".($node->data);
			// Visit left subtree
			$this->preOrder($node->left);
			// Visit right subtree
			$this->preOrder($node->right);
		}
	}
	public	function grandchildSum($node, $level)
	{
		if ($node != NULL)
		{
			$result = 0;
			if ($level > 2)
			{
				// Get the node
				$result = $node->data;
			}
			// Visit left subtree and right subtree
			return $result + 
              $this->grandchildSum($node->left, $level + 1) + 
              $this->grandchildSum($node->right, $level + 1);
		}
		else
		{
			return 0;
		}
	}
	public static function main()
	{
		// Create new binary trees
		$tree = new BinaryTree();
		/*
		         4   
		        /  \                          
		       /    \    
		      12     7    
		     / \      \               
		    2   3      1
		       / \    / 
		      6   8  5
		     /        
		    9                        
		  ----------------
		  Constructing binary tree    
		*/
		// Add nodes
		$tree->root = new TreeNode(4);
		$tree->root->left = new TreeNode(12);
		$tree->root->left->right = new TreeNode(3);
		$tree->root->left->right->left = new TreeNode(6);
		$tree->root->left->right->left->left = new TreeNode(9);
		$tree->root->left->right->right = new TreeNode(8);
		$tree->root->left->left = new TreeNode(2);
		$tree->root->right = new TreeNode(7);
		$tree->root->right->right = new TreeNode(1);
		$tree->root->right->right->left = new TreeNode(5);
		// Display tree node
		echo "\n Tree Nodes ";
		$tree->preOrder($tree->root);
		// Find node sum
		// 2 + 3 + 6 + 9 + 8 + 1 + 5 = 34
		$result = $tree->grandchildSum($tree->root, 1);
		// Display result
		echo "\n Result : ".($result), "\n";
	}
}
BinaryTree::main();

Output

 Tree Nodes   4  12  2  3  6  9  8  7  1  5
 Result : 34




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