LintCode632
来源:互联网 发布:mac php集成环境工具 编辑:程序博客网 时间:2024/06/07 01:02
二叉树的最大节点
在二叉树中寻找值最大的节点并返回。
给出如下一棵二叉树:
1 / \ -5 2 / \ / \0 3 -4 -5
返回值为 3
的节点。
代码:
class Solution {
public:
/**
* @param root the root of binary tree
* @return the max node
*/
TreeNode* maxNode(TreeNode* root) {
// Write your code here
if(root ==NULL)
return NULL;
TreeNode *max=root;
if(root->left !=NULL)
{
TreeNode *left=maxNode(root->left);//第一次漏掉这行,然后只能比较前三个。。。
max=max->val >left->val ? max:left;
}
if(root->right !=NULL)
{
TreeNode *right=maxNode(root->right);
max= max->val>right->val ? max:right;
}
return max;
}
};
/*若是刚入门对递归理解不深可以看如下:
class Solution {
public:
/**
* @param root the root of binary tree
* @return the max node
*/
TreeNode* maxNode(TreeNode* root) {
// Write your code here
if(root ==NULL)
return NULL;
TreeNode *max=root;
TreeNode *left=maxNode(root->left);
TreeNode *right=maxNode(root->right);
if(root->left !=NULL)
max=max->val >left->val ? max:left;
if(root->right !=NULL)
max= max->val>right->val ? max:right;
return max;
}
}; */