使用 C++ 列印二叉樹奇數層節點的程式


在本文中,我們將討論一個程式,用於列印給定二叉樹的奇數層中的節點。

此程式將根節點的層視為 1,同時替代層是下一個奇數層。

例如,假設我們使用以下二叉樹

然後,此二叉樹的奇數層中的節點將為 1、4、5、6。

示例

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node* left, *right;
};
//printing the nodes at odd levels
void print_onodes(Node *root, bool is_odd = true){
   if (root == NULL)
      return;
   if (is_odd)
      cout << root->data << " " ;
   print_onodes(root->left, !is_odd);
   print_onodes(root->right, !is_odd);
}
//creating a new node
struct Node* create_node(int data){
   struct Node* node = new Node;
   node->data = data;
   node->left = node->right = NULL;
   return (node);
}
int main(){
   struct Node* root = create_node(13);
   root->left = create_node(21);
   root->right = create_node(43);
   root->left->left = create_node(64);
   root->left->right = create_node(85);
   print_onodes(root);
   return 0;
}

輸出

13 64 85

更新於: 01-Nov-2019

115 次瀏覽

開啟您的 職業生涯

透過完成課程取得認證

開始
廣告
© . All rights reserved.