Code For NonGeek
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Level order traverse of a tree

Go down

Level order traverse of a tree Empty Level order traverse of a tree

Post  yangwenzhou Fri Sep 23, 2011 12:07 pm

Using DFS:
void printLevel(BinaryTree *p, int level) {
if (!p) return;
if (level == 1) {
cout << p->data << " ";
} else {
printLevel(p->left, level-1);
printLevel(p->right, level-1);
}
}

void printLevelOrder(BinaryTree *root) {
int height = maxHeight(root);
for (int level = 1; level <= height; level++) {
printLevel(root, level);
cout << endl;
}
}



Using one queue:
public void levelOrderOutput(TreeNode<E> root){
if(root==null)
return;
ArrayList<TreeNode<E>> queue=new ArrayList<TreeNode<E>>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode<E> head=queue.remove(0);
System.out.println(head.data()+" ");
if(ehad.left!=null)
queue.add(head.left);
if(head.right!=null)
queue.add(head.right);
}
}

yangwenzhou

Posts : 5
Join date : 2011-09-23

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum