Showing posts with label level order traversal. Show all posts
Showing posts with label level order traversal. Show all posts

Friday, December 27, 2013

Level Order Traversal for Binary Tree


    public void levelTraversal(TNode root) {
        TNodeQueue queue = new TNodeQueue();
        if(root != null){
            queue.push(root);
            while(!queue.isEmpty()){
                //System.out.println("Queue: " + queue.isEmpty());
                TNode tmp = queue.pop();
                System.out.print(tmp.data + " ");
                if(tmp.left != null)
                    queue.push(tmp.left);
                if(tmp.right != null)
                    queue.push(tmp.right);
            }
        }
    }

# output
Inorder:
2 4 6 8 9 10 

Level Order Traversal: 
8 4 9 2 6 10