Posted on by Kalkicode
Code Binary Tree

Diagonal traversal of binary tree in typescript

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

/* 
  TypeScript program for
  Diagonal Traversal of 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 diagonal elements
    public getDiagonalView(node: TreeNode, 
                          distance: number, 
                          record: Map)
    {
        if (node != null)
        {
            if (!record.has(distance))
            {
                // Add new diagonal level
                record.set(distance, []);
            }
            // Add node
            record.get(distance).push(node.data);
            // Visit to left subtree
            this.getDiagonalView(node.left, distance + 1, record);
            // Visit to right subtree
            this.getDiagonalView(node.right, distance, record);
        }
    }
    public diagonalView()
    {
        // This is store result
        var record = new Map();
        this.getDiagonalView(this.root, 0, record);
        var distance = 0;
        while (distance < record.size)
        {
            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 node
        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.diagonalView();
    }
}
BinaryTree.main();
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

[ 10, 4, 5 ]
[ 2, 6, 7, 3 ]
[ 3, 1, 9 ]

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