1. Level order traversal(BFS)

1. Level order traversal(BFS)


Problem link :- click here


package Binary_Tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BinaryTree__1
{
	static List<Integer> list = new ArrayList<>();
	
	static void levelOrderTraversal(BinaryTree tree)
	{
		Queue<Node> queue = new LinkedList<>();
		
		queue.add(tree.root);
		while( !queue.isEmpty() )
		{
			Node temp = queue.poll();
			System.out.print(temp.data + " ");
			
			if(temp.left != null)
				queue.add(temp.left);
			if(temp.right != null)
				queue.add(temp.right);
		}
	}
	
	static void BreadthFirstTraversal(Node root)
	{
		if(root == null   ||   (root.left == null   &&   root.right == null)  )
			return;
		
		if( list.isEmpty() )
			list.add(root.data);
		
		if(root.left != null)
			list.add(root.left.data);
		if(root.right != null)
			list.add(root.right.data);
		
		BreadthFirstTraversal(root.left);
		BreadthFirstTraversal(root.right);
		
	}
	
	public static void main(String[] args)
	{
		BinaryTree tree = new BinaryTree();
		int arr[] = {10, 20, 30, 40, 60};
		tree.root = tree.createTree(arr, 0);
		
		System.out.println("answer is : ");
		levelOrderTraversal(tree);
		
		BreadthFirstTraversal(tree.root);
		System.out.println();
		System.out.println(list);
	}

	static void printArray(int arr[])
	{
		for(int i=0; i<arr.length; i++)
			System.out.print(arr[i] + " ");
		System.out.println();
	}
}

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