Skip to main content

Triple order traversal of a binary tree in kotlin

Kotlin program for Triple order traversal of a binary tree. Here mentioned other language solution.

/*
    Kotlin program for
    Triple order traversal of a 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;
	}
	fun tripleOrder(node: TreeNode ? ): Unit
	{
		if (node != null)
		{
			// Print preorder node
			print(" " + node.data);
			// Visit left subtree
			this.tripleOrder(node.left);
			// Print inorder node
			print(" " + node.data);
			// Visit right subtree
			this.tripleOrder(node.right);
			// Print postorder node
			print(" " + node.data);
		}
	}
}
fun main(args: Array < String > ): Unit
{
	// Create new binary trees
	val tree: BinaryTree = BinaryTree();
	/*
	         4    
	        / \                         
	       /   \    
	     -4     7    
	     / \     \               
	    2   3     1
	       / \   / 
	      6   8 5
	     /       
	    9          
	  ----------------------
	  Constructing binary tree
	        
	*/
	tree.root = TreeNode(4);
	tree.root?.left = TreeNode(-4);
	tree.root?.left?.right = TreeNode(3);
	tree.root?.left?.right?.left = TreeNode(6);
	tree.root?.left?.right?.left?.left = TreeNode(9);
	tree.root?.left?.right?.right = TreeNode(8);
	tree.root?.left?.left = TreeNode(2);
	tree.root?.right = TreeNode(7);
	tree.root?.right?.right = TreeNode(1);
	tree.root?.right?.right?.left = TreeNode(5);
	// Print triple order
	// ----------------------------------
	// 4 -4 2 2 2 -4 3 6 9 9 9 6 6 3 8 8 ..
	// 8 3 -4 4 7 7 1 5 5 5 1 1 7 4
	tree.tripleOrder(tree.root);
}

Output

 4 -4 2 2 2 -4 3 6 9 9 9 6 6 3 8 8 8 3 -4 4 7 7 1 5 5 5 1 1 7 4




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