一、问题描述
在二叉树中寻找值最大的节点并返回。
二、样例
给出如下一棵二叉树:
1
/ \
-5 2
/ \ / \
0 3 -4 -5
返回值为 3
的节点。
若树为空,则返回空;若不为空,则遍历找出最大数。
四、代码
lass Solution {
public:
/**
* @param root the root of binary tree
* @return the max node
*/
TreeNode *t=new TreeNode(-100);
TreeNode* maxNode(TreeNode* root) {
if(root==NULL) return NULL;
else {
if(root->val>t->val)
t=root;
maxNode(root->left);
maxNode(root->right);
return t;}
// Write your code here
}
};
五、个人感悟
若树为空,则返回空;若不为空,则遍历找出最大数。