写一段代码来查找二叉树中的最大值
时间: 2024-05-01 10:17:47 浏览: 13
当然,我会安静地听取您的问题并为您提供合适的答案。下面是您要求的代码,用于查找二叉树中的最大值。
```
#include<iostream>
using namespace std;
struct Node{
int data;
Node *left;
Node *right;
Node(int x){
data=x;
left=NULL;
right=NULL;
}
};
int maximumValue(Node *root){
if(root==NULL) return INT_MIN;
return max(root->data, max(maximumValue(root->left),maximumValue(root->right)));
}
int main(){
// create binary tree
Node *root=new Node(10);
root->left=new Node(5);
root->right=new Node(15);
root->left->left=new Node(3);
root->left->right=new Node(8);
root->right->left=new Node(12);
root->right->right=new Node(18);
// find maximum value in binary tree
cout<<"Maximum value in binary tree is: "<<maximumValue(root)<<endl;
return 0;
}
```
当您运行这段代码时,您将看到输出:
```
Maximum value in binary tree is: 18
```
这意味着,在上面的示例中,树中的最大值为 18。希望这个答案对您有帮助!