C++ program to print the nodes at odd level odd of a tree














































C++ program to print the nodes at odd level odd of a tree



Description: This code print nodes at odd levels of a tree. Variable rev is a boolean type variable which is by default true for the root node. The root node is declared as an odd node and subsequent odd levels are printed out. If the tree is not present then the program will print 0.


#include<iostream> using namespace std; class Node { public: int data; Node *left, *right; }; void printoddnodes(Node* root, bool rev = true) { //If the tree is empty or not if (root == NULL) return; //rev changes after every level parsed which only lets odd level to pass-through if (rev) cout << root->data << " "; printoddnodes(root->left, !rev); printoddnodes(root->right, !rev); } //to create new empty node class Node* newNode(int data) { class Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } int main() { //creating tree class Node* root = newNode(10); root->left = newNode(20); root->right = newNode(30); root->left->left = newNode(40); root->left->right = newNode(50); printoddnodes(root); return 0; }

Input:(will be like this in tree format)

        10
        /  \
     20   30
     /  \
  40  50

Output:10 40 50

Comments