1.问题描述
在二叉树中寻找值最大的节点并返回。
样例
给出如下一棵二叉树:
1
/ \
-5 2
/ \ / \
0 3 -4 -5
返回值为 3
的节点。
2.解题思路
定义一个全局变量,赋值一个很小的数,然后在函数内递归调用节点进行比较,找出最大值。
3.代码实现
class Solution {
public:
/**
* @param root the root of binary tree
* @return the max node
*/
TreeNode*m=new TreeNode(-10000000);
TreeNode* maxNode(TreeNode* root) {
// Write your code here
if(root==NULL)
return NULL;
else {
if(root->val>m->val) m=root;
maxNode(root->left);
maxNode(root->right);
}
return m;
}
};
4.感想
重点在于全局变量的定义,定义全局变量的意义就在于只调用一次,不重复调用。