在 C++ 编程中打印树中的奇数层节点。


给定二叉树,该程序必须打印奇数层上的节点,而二叉树的层级从 1 开始到 n。

由于尚未提及,因此可以实现两种方法之一,即递归或迭代。

由于我们正在使用递归方法,所以程序将递归地调用一个函数,该函数将获取奇数层上的节点并返回它们。

在上述二叉树中 -

Nodes at level 1: 10
Nodes at level 2: 3 and 211
Nodes at level 3: 140, 162, 100 and 146

因此,将打印第 1 层和第 3 层的节点,这意味着输出将为 10、140、162、100 和 146。

算法

START
Step 1 -> create a structure of a node as
   struct Node
      struct node *left, *right
      int data
   End
Step 2 -> function to create a node
   node* newnode(int data)
   node->data = data
   node->left = node->right = NULL;
   return (node)
step 3 -> create function for finding the odd nodes
   void odd(Node *root, bool ifodd = true)
   IF root = NULL
      Return
   End
   if (ifodd)
      print root->data
   End
   odd(root->left, !ifodd)
   odd(root->right, !ifodd)
step 4 -> In main()
   Create tree using Node* root = newnode(45)
   root->left = newnode(23)
   Call odd(root)
Stop

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
struct Node{
   int data;
   Node* left, *right;
};
void odd(Node *root, bool ifodd = true){
   if (root == NULL)
      return;
   if (ifodd)
      cout << root->data << " " ;
   odd(root->left, !ifodd);
   odd(root->right, !ifodd);
}
// function to create a new node
Node* newnode(int data){
   Node* node = new Node;
   node->data = data;
   node->left = node->right = NULL;
   return (node);
}
int main(){
   Node* root = newnode(45);
   root->left = newnode(23);
   root->right = newnode(13);
   root->left->left = newnode(24);
   root->left->right = newnode(85);
   cout<<"\nodd nodes are ";
   odd(root);
   return 0;
}

输出

如果我们运行上述程序,它将生成以下输出

odd nodes are 45 24 85

更新于:04-Sep-2019

108 浏览次数

开启您的职业生涯

通过完成课程获得认证

开始使用
广告
© . All rights reserved.