Posted on by Kalkicode
Code Binary Tree

Diagonal traversal of binary tree in kotlin

Kotlin program for Diagonal traversal of binary tree. Here problem description and explanation.

/* 
  Kotlin program for
  Diagonal Traversal of Binary Tree
*/
// Binary Tree Node
class TreeNode
{
    var data: Int;
    var left: TreeNode ? ;
    var right: TreeNode ? ;
    constructor(data: Int)
    {
        // Set node value
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
class BinaryTree
{
    var root: TreeNode ? ;
    constructor()
    {
        this.root = null;
    }
    // Find diagonal elements
    fun getDiagonalView(node: TreeNode ? , 
                       distance : Int, 
                 record: HashMap < Int, MutableList < Int >>  ): Unit
    {
        if (node != null)
        {
            if (!record.containsKey(distance))
            {
                // Add new diagonal level
                record.put(distance, mutableListOf < Int > ());
            }
            // Add node
            record.getValue(distance).add(node.data);
            // Visit to left subtree
            this.getDiagonalView(node.left, distance + 1, record);
            // Visit to right subtree
            this.getDiagonalView(node.right, distance, record);
        }
    }
    fun diagonalView(): Unit
    {
        // This is store result
        val record: HashMap < Int, MutableList < Int >> = 
          HashMap < Int, MutableList < Int >> ();
        this.getDiagonalView(this.root, 0, record);
        var distance: Int = 0;
        while (distance < record.count())
        {
            // This loop display diagonal element
            for (v in record.getValue(distance))
            {
                print("  " + v);
            }
            println();
            distance += 1;
        }
    }
}
fun main(args: Array < String > ): Unit
{
    // Create new tree
    val tree: BinaryTree = BinaryTree();
    /*
     Make A Binary Tree
     -----------------------
          10
         / \ 
        /   \
       2     4
      /    /  \
     3    6    \
         / \    \
        1   7    5
           /    /
          9    3 
    */
    // Add tree node
    tree.root = TreeNode(10);
    tree.root?.left = TreeNode(2);
    tree.root?.left?.left = TreeNode(3);
    tree.root?.right = TreeNode(4);
    tree.root?.right?.right = TreeNode(5);
    tree.root?.right?.left = TreeNode(6);
    tree.root?.right?.left?.left = TreeNode(1);
    tree.root?.right?.right?.left = TreeNode(3);
    tree.root?.right?.left?.right = TreeNode(7);
    tree.root?.right?.left?.right?.left = TreeNode(9);
    tree.diagonalView();
}

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