
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find maximum (or minimum) in Binary Tree in C++
In this problem, we are given a binary tree. Our task is to Find maximum (or minimum) in Binary Tree.
Problem Description: We need to find the nodes of the binary tree that have maximum and minimum value in the binary tree.
Let’s take an example to understand the problem,
Input:
Output: max = 9 , min = 1
Solution Approach
We need to find the max node of the binary tree. We will do this by traversing the pointer until we reach the leaf node and then find the maximum node of the tree.
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; class Node { public: int data; Node *left, *right; Node(int data) { this->data = data; this->left = NULL; this->right = NULL; } }; int findMaxNode(Node* root) { if (root == NULL) return -100; int maxVal = root->data; int leftMaxVal = findMaxNode(root->left); int rightMaxVal = findMaxNode(root->right); if (leftMaxVal > maxVal) maxVal = leftMaxVal; if (rightMaxVal > maxVal) maxVal = rightMaxVal; return maxVal; } int main() { Node* NewRoot = NULL; Node* root = new Node(5); root->left = new Node(3); root->right = new Node(2); root->left->left = new Node(1); root->left->right = new Node(8); root->right->left = new Node(6); root->right->right = new Node(9); cout<<"The Maximum element of Binary Tree is "<<findMaxNode(root) << endl; return 0; }
Output
The Maximum element of Binary Tree is 9
- Related Articles
- Searching for minimum and maximum values in an Javascript Binary Search Tree
- Find maximum level product in Binary Tree in C++
- Find maximum vertical sum in binary tree in C++
- Find maximum level sum in Binary Tree in C++
- Find Minimum Depth of a Binary Tree in C++
- Maximum Binary Tree in C++
- Maximum Binary Tree II in C++
- Minimum Depth of Binary Tree in C++
- Find maximum among all right nodes in Binary Tree in C++
- Maximum Width of Binary Tree in C++
- Maximum Depth of Binary Tree in Python
- Binary Tree Maximum Path Sum in Python
- Maximum spiral sum in Binary Tree in C++
- Maximum Sum BST in Binary Tree in C++
- Binary Indexed Tree or Fenwick Tree in C++?

Advertisements