Posted on by Kalkicode
Code Binary Tree

Diagonal sum of a binary tree in typescript

Ts program for Diagonal sum of a binary tree. Here problem description and other solutions.

/* 
  TypeScript program for
  Diagonal sum of a binary tree
*/
// 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;
	}
	// Find sum of diagonal elements
	public getDiagonalSum(node: TreeNode, 
                          distance: number, 
                          record: Map)
	{
		if (node != null)
		{
			if (record.has(distance))
			{
				// Update value
				record.set(distance, record.get(distance) + node.data);
			}
			else
			{
				// Add new element
				record.set(distance, node.data);
			}
			this.getDiagonalSum(node.left, distance + 1, record);
			this.getDiagonalSum(node.right, distance, record);
		}
	}
	public diagonalSum()
	{
		// This is store result
		var record = new Map();
		this.getDiagonalSum(this.root, 0, record);
		var distance = 0;
		// This loop display diagonal sum
		while (distance < record.size)
		{
			// Display sum
			console.log("  " + record.get(distance));
			distance += 1;
		}
	}
	public static main()
	{
		// Create new tree
		var tree = new BinaryTree();
		/*
		 Make A Binary Tree
		   -------------------
		          10
		         / \ 
		        /   \
		       2     4
		      /    /  \
		     3    6    \
		         / \    \
		        1   7    5
		           /    /
		          9    3 
		*/
		// Add tree nodes
		tree.root = new TreeNode(10);
		tree.root.left = new TreeNode(2);
		tree.root.left.left = new TreeNode(3);
		tree.root.right = new TreeNode(4);
		tree.root.right.right = new TreeNode(5);
		tree.root.right.left = new TreeNode(6);
		tree.root.right.left.left = new TreeNode(1);
		tree.root.right.right.left = new TreeNode(3);
		tree.root.right.left.right = new TreeNode(7);
		tree.root.right.left.right.left = new TreeNode(9);
		tree.diagonalSum();
	}
}
BinaryTree.main();
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

  19
  18
  13

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