
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
Depth of the Deepest Odd Level Node in Binary Tree in C++
In this tutorial, we are going to learn how to find the deepest odd level node in a binary tree.
This is similar to finding the depth of the binary tree. Here, we have to one more condition i.e.., whether the current level is odd or not.
Let's see the steps to solve the problem.
Initialize the binary tree with dummy data.
-
Write a recursive function to find the deepest odd level node in a binary tree.
If the current node is a leaf node and the level is odd, then return the current level.
Else return the max of left node and right node with recursive function calls.
Print the deepest odd level node.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *left, *right; }; struct Node* newNode(int data) { struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node; } int oddLeafDepthInTree(struct Node *root, int level) { if (root == NULL) { return 0; } if (root->left == NULL && root->right == NULL && level % 2 == 1) { return level; } return max(oddLeafDepthInTree(root->left, level + 1), oddLeafDepthInTree(root->right, level + 1)); } int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); int level = 1, depth = 0; cout << oddLeafDepthInTree(root, level) << endl; return 0; }
Output
If you execute the above code, then you will get the following result.
3
Conclusion
If you have any queries in the tutorial, mention them in the comment section.