【入门】lintcode 632: 二叉树的最大节点
2018-01-15 11:21
204 查看
在二叉树中寻找值最大的节点并返回。
样例
给出如下一棵二叉树:
返回值为
当然是递归。
/**
* Definition of TreeNode:
* 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 * max = root;
if(root->left != NULL)
{
TreeNode * left1 = maxNode(root->left);
max = max->val > left1->val ? max : left1;
}
if(root->right != NULL)
{
TreeNode * right1 = maxNode(root->right);
max = max->val > right1->val ? max : right1;
}
return max;
}
};
样例
给出如下一棵二叉树:
1 / \ -5 2 / \ / \ 0 3 -4 -5
返回值为
3的节点。
当然是递归。
/**
* Definition of TreeNode:
* 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 * max = root;
if(root->left != NULL)
{
TreeNode * left1 = maxNode(root->left);
max = max->val > left1->val ? max : left1;
}
if(root->right != NULL)
{
TreeNode * right1 = maxNode(root->right);
max = max->val > right1->val ? max : right1;
}
return max;
}
};
相关文章推荐
- Lintcode 入门-632. 二叉树的最大节点
- 【LintCode 入门】632. 二叉树的最大节点
- LintCode入门练习——632. 二叉树的最大节点
- LintCode入门练习——632. 二叉树的最大节点
- LintCode-(632)二叉树的最大节点
- lintcode 632. 二叉树的最大节点
- 【LintCode-632】二叉树的最大节点(Java实现)
- LintCode之632 二叉树最大节点
- 二叉树的最大节点-LintCode
- LintCode 二叉树的最大节点
- 二叉树最大节点-lintCode
- 632. 二叉树的最大节点(java)
- 二叉树的最大节点-LintCode
- LintCode 第632题 二叉树的最大节点
- LintCode:二叉树的最大节点632
- [Lintcode]二叉树的最大节点
- 一、lintcode刷题记录--矩阵面积、二叉树的最大节点、整数排序、删除链表中的元素
- (lintcode)第632题二叉树的最大节点
- LintCode 二叉树的最大节点
- LintCode-二叉树的最大节点