用 C++ 找出二叉樹中所有右節點的最大值


在這個教程中,我們得到一棵二叉樹。我們的任務是找出二叉樹中所有右節點的最大值。 

問題說明: 我們需要在這棵二叉樹的右子節點中找出最大值。

舉個例子來理解問題, 

輸入: 


輸出: 9

說明: 

所有右節點有:{2, 8, 9}。它們的最大值是 9。

解決方案

為了解決這個問題,我們需要遍歷這棵樹,並檢查它是否有右子節點。如果有,就將它與 maxRight 元素進行比較,如果較大就進行替換。

演示我們解決方案的程式:

示例

線上演示

#include <iostream>
using namespace std;

struct Node {
   int data;
   struct Node *left, *right;
};

Node* newNode(int data) {
   
   Node* temp = new Node;
   temp->data = data;
   temp->left = temp->right = NULL;
   return temp;
}

int findMaxRightNode(Node* root) {
   
   int maxRight = -100;

   if (root == NULL)
      return -1;

   if (root->right != NULL)
      maxRight = root->right->data;

   return max( findMaxRightNode(root->right), max(maxRight, findMaxRightNode(root->left) ) );
}

int main() {

   Node* root = newNode(5);
   root->left = newNode(3);
   root->right = newNode(2);
   root->left->left = newNode(1);
   root->left->right = newNode(8);
   root->right->left = newNode(6);
   root->right->right = newNode(9);

   cout<<"The maximum among all right nodes in Binary Tree is "<< findMaxRightNode(root);

   return 0;
}

輸出

The maximum among all right nodes in Binary Tree is 9

更新於:2021-01-25

55 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

立即開始
廣告
© . All rights reserved.