
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print All Even Nodes of Binary Search Tree in C++
In this problem, we are given a binary search tree. Our task is to print all even valued nodes of the binary search tree.
The binary search tree is a binary tree that follows the following condition −
The left sub-tree always contains nodes with smaller values than the parent node.
Right, sub-tree always contains nodes with greater values than the parent node.
All nodes have to follow the above 2 rules.
Example of a binary search tree −
Let’s take an example to understand the problem −
Output − 2 4 6 8
To solve this problem, we will have to traverse all nodes of the binary search tree and check for the current node’s value. If it is even then print the node otherwise leave it.
Example
The below code will illustrate the working of our logic −
#include <iostream> using namespace std; struct Node { int key; struct Node *left, *right; }; Node* newNode(int item){ Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp; } Node* insertNode(Node* node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insertNode(node->left, key); else node->right = insertNode(node->right, key); return node; } void printEvenNode(Node* root){ if (root != NULL) { printEvenNode(root->left); if (root->key % 2 == 0) cout<<root->key<<"\t"; printEvenNode(root->right); } } int main(){ Node* root = NULL; root = insertNode(root, 54); root = insertNode(root, 43); root = insertNode(root, 12); root = insertNode(root, 30); root = insertNode(root, 89); root = insertNode(root, 67); root = insertNode(root, 80); cout<<"All even nodes of the tree are :\n"; printEvenNode(root); return 0; }
Output
All even nodes of the tree are −
12 30 54 80