C++ 中查找二叉树中的最大值(或最小值)


在此题中,我们给定一颗二叉树。我们的任务是在二叉树中查找最大值(或最小值)。

问题描述:我们需要查找二叉树中具有最大值和最小值的节点。

我们举个例子来理解这个问题,

输入: 


输出:max = 9,min = 1

解决方案

我们需要找到二叉树的最大节点。我们将这样做,即,一直遍历指针,直到到达叶节点,然后找到这棵树的最大节点。

程序说明解决方案的工作原理,

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

实例

在线演示

#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;
}

输出

The Maximum element of Binary Tree is 9

更新于: 2021-1-25

894 次浏览

启动你的职业

通过完成课程获得认证

开始
广告