Insertion in binary search tree using recursion in swift

Swift program for Insertion in binary search tree using recursion. Here problem description and explanation.

import Foundation
// Swift 4 program for
// Insertion in binary search tree by using recursion
class TreeNode
{
	var data: Int;
	var left: TreeNode? ;
	var right: TreeNode? ;
	init(_ data: Int)
	{
		self.data = data;
		self.left = nil;
		self.right = nil;
	}
}
class BinarySearchTree
{
	var root: TreeNode? ;
	init()
	{
		self.root = nil;
	}
	// Insert a node element
	func insert(_ node: TreeNode? , _ data : Int) -> TreeNode?
	{
		if (node  != nil)
		{
			if (node!.data >= data)
			{
				// When new element is smaller or
				// equal to current node
				node!.left = self.insert(node!.left, data);
			}
			else
			{
				// When new element is higher to current node
				node!.right = self.insert(node!.right, data);
			}
			// important to manage root node
			return node;
		}
		else
		{
			return TreeNode(data);
		}
	}
	// Display preorder
	func preorder(_ node: TreeNode? )
	{
		if (node  != nil)
		{
			// Display node value
			print(" ", node!.data, terminator: "");
			// Visit to left subtree
			self.preorder(node!.left);
			// Visit to right subtree
			self.preorder(node!.right);
		}
	}
	func inorder(_ node: TreeNode? )
	{
		if (node  != nil)
		{
			// Visit to left subtree
			self.inorder(node!.left);
			// Display node value
			print(" ", node!.data, terminator: "");
			// Visit to right subtree
			self.inorder(node!.right);
		}
	}
	func postorder(_ node: TreeNode? )
	{
		if (node  != nil)
		{
			// Visit to left subtree
			self.postorder(node!.left);
			// Visit to right subtree
			self.postorder(node!.right);
			// Display node value
			print(" ", node!.data, terminator: "");
		}
	}
	func addNode(_ data: Int)
	{
		self.root = insert(self.root, data);
	}
	static func main()
	{
		let tree: BinarySearchTree = BinarySearchTree();
		/*
		         10
		        / \
		       /   \
		      4     15
		     / \   /
		    3   5 12
		    -------------
		    Build binary search tree
		*/
		tree.addNode(10);
		tree.addNode(4);
		tree.addNode(3);
		tree.addNode(5);
		tree.addNode(15);
		tree.addNode(12);
		// Display tree nodes
		print("Preorder ");
		tree.preorder(tree.root);
		print("\nInorder ");
		tree.inorder(tree.root);
		print("\nPostorder ");
		tree.postorder(tree.root);
	}
}
BinarySearchTree.main();

Output

Preorder
  10  4  3  5  15  12
Inorder
  3  4  5  10  12  15
Postorder
  3  5  4  12  15  10


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