在二叉树中寻找值最大的节点并返回。
样例:
给出如下一棵二叉树:
1
/ \
-5 2
/ \ / \
0 3 -4 -5
返回值为 3 的节点。
#ifndef C632_H
#define C632_H
#include<iostream>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int val)
{
this->val = val;
this->left = this->right = NULL;
}
};
class Solution {
public:
/*
* @param root: the root of tree
* @return: the max node
*/
TreeNode * maxNode(TreeNode * root) {
// write your code here
if (root == NULL)
return NULL;
TreeNode *p = root;
if (root->left != NULL)
p = maxVal(p, maxNode(root->left));
if (root->right != NULL)
p = maxVal(p, maxNode(root->right));
return p;
}
TreeNode* maxVal(TreeNode *a, TreeNode *b)
{
return a->val > b->val ? a : b;
}
};
#endif