首页 > 代码库 > Printing a Binary Tree in Level Orders

Printing a Binary Tree in Level Orders

BFS:

Is it possible that a solution exists using only one single queue? Yes, you bet. The single queue solution requires two extra counting variables which keep tracks of the number of nodes in the current level (nodesInCurrentLevel) and the next level (nodesInNextLevel). When we pop a node off the queue, we decrement nodesInCurrentLevel by one. When we push its child nodes to the queue, we incrementnodesInNextLevel by two. When nodesInCurrentLevel reaches 0, we know that the current level has ended, therefore we print an endline here

void printLevelOrder(BinaryTree *root) {  if (!root) return;  queue<BinaryTree*> nodesQueue;  int nodesInCurrentLevel = 1;  int nodesInNextLevel = 0;  nodesQueue.push(root);  while (!nodesQueue.empty()) {    BinaryTree *currNode = nodesQueue.front();    nodesQueue.pop();    nodesInCurrentLevel--;    if (currNode) {      cout << currNode->data << " ";      nodesQueue.push(currNode->left);      nodesQueue.push(currNode->right);      nodesInNextLevel += 2;    }    if (nodesInCurrentLevel == 0) {      cout << endl;      nodesInCurrentLevel = nodesInNextLevel;      nodesInNextLevel = 0;    }  }}

 

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;  }}

 

 

 

Printing a Binary Tree in Level Orders