用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP