Skip to main content

Sum of leaf node in BST using recursion in c++

Sum of leaf nodes

C++ program for Sum of leaf node in BST using recursion. Here mentioned other language solution.

// Include header file
#include <iostream>
using namespace std;
// C++ program for
// Sum of all leaf nodes of binary search tree
// Using recusion
class TreeNode
{
	public: int data;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int data)
	{
		this->data = data;
		this->left = nullptr;
		this->right = nullptr;
	}
};
class BinarySearchTree
{
	public: TreeNode *root;
	BinarySearchTree()
	{
		this->root = nullptr;
	}
	// insert a new node
	void addNode(int data)
	{
		// Create a new node
		TreeNode *node = new TreeNode(data);
		if (this->root == nullptr)
		{
			// When adds a first node in bst
			this->root = node;
		}
		else
		{
			TreeNode *find = this->root;
			// Add new node to proper position
			while (find != nullptr)
			{
				if (find->data >= data)
				{
					if (find->left == nullptr)
					{
						// 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 == nullptr)
					{
						// 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
	int leafNodeSum(TreeNode *node)
	{
		if (node != nullptr)
		{
			if (node->left == nullptr && node->right == nullptr)
			{
				// 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;
	}
};
int main()
{
	BinarySearchTree *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
	cout << tree->leafNodeSum(tree->root);
	return 0;
}

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