使用 C++ 列印二叉樹中兩個給定級別節點的程式


在本教程中,將探討列印二叉樹兩個給定級別節點的程式。

在這裡,將為特定二叉樹設定低級別和高級別,並且我們必須列印給定級別之間的所有元素。

要解決此問題,可以使用基於佇列的級別遍歷。在中序遍歷中移動時,可以在每個級別的末尾設定一個標記節點。然後,我們可以進入每個級別並列印其節點,如果標記節點存在於給定級別之間,就可以列印其節點。

示例

#include <iostream>
#include <queue>
using namespace std;
struct Node{
   int data;
   struct Node* left, *right;
};
//to print the nodes between the levels
void print_nodes(Node* root, int low, int high){
   queue <Node *> Q;
   //creating the marking node
   Node *marker = new Node;
   int level = 1;
   Q.push(root);
   Q.push(marker);
   while (Q.empty() == false){
      Node *n = Q.front();
      Q.pop();
      //checking for the end of level
      if (n == marker){
      cout << endl;
      level++;
      if (Q.empty() == true || level > high)
      break;
      Q.push(marker);
      continue;
   }
   if (level >= low)
      cout << n->data << " ";
      if (n->left != NULL) Q.push(n->left);
      if (n->right != NULL) Q.push(n->right);
   }
}
Node* create_node(int data){
   Node* temp = new Node;
   temp->data = data;
   temp->left = temp->right = NULL;
   return (temp);
}
int main(){
   struct Node *root= create_node(20);
   root->left= create_node(8);
   root->right= create_node(22);
   root->left->left= create_node(4);
   root->left->right= create_node(12);
   root->left->right->left= create_node(10);
   root->left->right->right= create_node(14);
   cout << "Elements between the given levels are :";
   print_nodes(root, 2, 3);
   return 0;
}

輸出

Elements between the given levels are :
8 22
4 12

更新於:01-11-2019

104 次瀏覽

啟動你的 職業生涯

完成課程即可獲得認證

開始行動
廣告
© . All rights reserved.