Printing a binary tree in level orders

Source: Internet
Author: User

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 decrementNodesincurrentlevelByOne. When we push its child nodes to the queue, We IncrementNodesinnextlevelByTwo. WhenNodesincurrentlevelReaches0, 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.