LintCode 二叉树的最大节点

题目描述:

在二叉树中寻找值最大的节点并返回。

样例
给出如下一棵二叉树:

1
/ \
-5 2
/ \ / \
0 3 -4 -5
返回值为 3 的节点。

思路分析:

遍历一遍记录最大值。

ac代码:

class Solution {
public:
    /**
     * @param root the root of binary tree
     * @return the max node
     */
    int maxx=-99999;
    TreeNode *nmax;
    void max(TreeNode *root)
    {
        if(root==NULL)
            return ;
        if(root->val>maxx)
        {
            maxx=root->val;
            nmax=root;
        }
        max(root->left);
        max(root->right);
    }
    TreeNode* maxNode(TreeNode* root) {
        // Write your code here
        if(root==NULL)
            return NULL;
        max(root);
        return nmax;
    }
};
发布了166 篇原创文章 · 获赞 4 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/sinat_34336698/article/details/69787558
今日推荐