Inorder traversal of binary tree with recursion in kotlin

Kotlin program for Inorder traversal of binary tree with recursion. Here problem description and explanation.

/* 
  Kotlin Program for
  inorder tree traversal of a Binary Tree
  using recursion
*/
// 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;
	}
	// Display Inorder view of binary tree
	fun inorder(node: TreeNode ? ): Unit
	{
		if (node != null)
		{
			// Visit left subtree
			this.inorder(node.left);
			//Print node value
			print("  " + node.data);
			// Visit right subtree
			this.inorder(node.right);
		}
	}
}
fun main(args: Array < String > ): Unit
{
	// Create new tree
	val tree: BinaryTree = BinaryTree();
	/*
	    Make A Binary Tree
	    ----------------
	        15
	       /  \
	      24   54
	     /    /  \
	    35   62   13
	*/
	// Add tree TreeNode
	tree.root = TreeNode(15);
	tree.root?.left = TreeNode(24);
	tree.root?.right = TreeNode(54);
	tree.root?.right?.right = TreeNode(13);
	tree.root?.right?.left = TreeNode(62);
	tree.root?.left?.left = TreeNode(35);
	// Display Tree Node
	tree.inorder(tree.root);
}

Output

  35  24  15  62  54  13


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







© 2021, kalkicode.com, All rights reserved