C++ 中查詢二叉樹中的最大值(或最小值)


在此題中,我們給定一顆二叉樹。我們的任務是在二叉樹中查詢最大值(或最小值)。

問題描述:我們需要查詢二叉樹中具有最大值和最小值的節點。

我們舉個例子來理解這個問題,

輸入: 


輸出:max = 9,min = 1

解決方案

我們需要找到二叉樹的最大節點。我們將這樣做,即,一直遍歷指標,直到到達葉節點,然後找到這棵樹的最大節點。

程式說明解決方案的工作原理,

例項

線上演示

#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 次瀏覽

啟動你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.