Skip to main content

Sum of all right leaf nodes of binary tree in node js

Sum of all right leaf nodes in binary tree

Js program for Sum of all right leaf nodes of binary tree. Here mentioned other language solution.

/*
    Node JS program for
    Sum of all right leaves nodes in a binary tree
    Using recursion
*/
// Binary Tree node
class TreeNode
{
	constructor(data)
	{
		// Set node value
		this.data = data;
		this.left = null;
		this.right = null;
	}
}
class BinaryTree
{
	constructor()
	{
		this.root = null;
	}
	// Display pre order elements
	preorder(node)
	{
		if (node != null)
		{
			// Print node value
			process.stdout.write("  " + node.data);
			this.preorder(node.left);
			this.preorder(node.right);
		}
	}
	// Returns the Sum of all the right leaves in binary tree
	rightLeavesSum(node)
	{
		var sum = 0;
		if (node != null)
		{
			if (node.right != null && 
                node.right.left == null && 
                node.right.right == null)
			{
				// When get right leaf node
				sum = node.right.data;
			}
			// Recursively visit left and right subtree.
			// And find sum of right leaf nodes
			sum = sum + this.rightLeavesSum(node.left) +
              this.rightLeavesSum(node.right);
		}
		return sum;
	}
}

function main()
{
	// New binary tree
	var tree = new BinaryTree();
	/*
	    Constructor binary tree
	    -----------------------
	          6
	         / \ 
	        /   \                             
	       /     \    
	      2       3     
	     / \       \               
	    8   10      1
	       /  \    / \
	      6   -2  4   5
	*/
	// Add tree node
	tree.root = new TreeNode(6);
	tree.root.left = new TreeNode(2);
	tree.root.left.left = new TreeNode(8);
	tree.root.left.right = new TreeNode(10);
	tree.root.left.right.right = new TreeNode(-2);
	tree.root.left.right.left = new TreeNode(6);
	tree.root.right = new TreeNode(3);
	tree.root.right.right = new TreeNode(1);
	tree.root.right.right.left = new TreeNode(4);
	tree.root.right.right.right = new TreeNode(5);
	process.stdout.write("\n Tree Nodes : ");
	tree.preorder(tree.root);
	// Find right leaf sum
	var sum = tree.rightLeavesSum(tree.root);
	// Display result
	process.stdout.write("\n Right leaves nodes sum : " + sum);
}
// Start program execution
main();

Output

 Tree Nodes :   6  2  8  10  6  -2  3  1  4  5
 Right leaves nodes sum : 3




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