Level order traverse of a tree

View previous topic View next topic Go down

Level order traverse of a tree

Post  yangwenzhou on 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

View user profile

Back to top Go down

View previous topic View next topic Back to top

- Similar topics

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