Skip to main content

Sum of all right leaf nodes of binary tree in typescript

Sum of all right leaf nodes in binary tree

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

/*
    TypeScript program for
    Sum of all right leaves nodes in a binary tree
    Using recursion
*/
// Binary Tree node
class TreeNode
{
	public data: number;
	public left: TreeNode;
	public right: TreeNode;
	constructor(data: number)
	{
		// Set node value
		this.data = data;
		this.left = null;
		this.right = null;
	}
}
class BinaryTree
{
	public root: TreeNode;
	constructor()
	{
		// Set initial tree root
		this.root = null;
	}
	// Display pre order elements
	public preorder(node: TreeNode)
	{
		if (node != null)
		{
			// Print node value
			console.log("  " + node.data);
			this.preorder(node.left);
			this.preorder(node.right);
		}
	}
	// Returns the Sum of all the right leaves in binary tree
	public number rightLeavesSum(node: TreeNode)
	{
		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;
	}
	public static 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);
		console.log("\n Tree Nodes : ");
		tree.preorder(tree.root);
		// Find right leaf sum
		var sum = tree.rightLeavesSum(tree.root);
		// Display result
		console.log("\n Right leaves nodes sum : " + sum);
	}
}
BinaryTree.main();
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

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