6. In-order traversal

6. In-order traversal


Problem link :- click here


package Binary_Tree;

import java.util.Stack;

public class BinaryTree__6
{
	
	static void inOrderRecursive(Node root)
	{
		if(root == null)
			return;
		
		inOrderRecursive(root.left);
		System.out.print(root.data + "  ");
		inOrderRecursive(root.right);
	}
	
	static void inOrderIterative(Node root)
	{
		if(root == null)
			return;
		
		Stack<Node> stack = new Stack<>();
		
		Node cur = root;
		while( !stack.isEmpty() ||  cur != null)
		{
			if(cur != null)
			{
				stack.push(cur);
				cur = cur.left;
			}
			else
			{
				cur = stack.pop();
				System.out.print(cur.data + "  ");
				cur = cur.right;
			}
		}
	}

	public static void main(String[] args)
	{
		BinaryTree tree = new BinaryTree();
		int arr[] = {10, 20, 30, 40, 60};
		tree.root = tree.createTree(arr, 0);
		
		inOrderIterative(tree.root);
		System.out.println();
		inOrderRecursive(tree.root);
	}

}

Time complexity :- O(n)
Space complexity :- O(n)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree