Lintcode:二叉树的最大节点

来源:互联网 发布:chrome网络商店 编辑:程序博客网 时间:2024/06/06 12:24

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

样例

给出如下一棵二叉树:

     1   /   \ -5     2 / \   /  \0   3 -4  -5 

返回值为 3 的节点。


python:

class Solution:    """    @param: root: the root of tree    @return: the max node    """    def maxNode(self, root):        # write your code here        if root is None:            return        self.max(root)        return self.node    maxVal = -9999    node = None    def max(self, root):        if root is None:            return        if root.val >= self.maxVal:            self.maxVal = root.val            self.node = root        self.max(root.left)        self.max(root.right)


C++:

class Solution {public:    /*     * @param root: the root of tree     * @return: the max node     */    int maxx=-99999;    TreeNode *pmax;    void max(TreeNode *root)    {        if(root==NULL)            return ;        if(root->val>maxx)        {            maxx=root->val;            pmax=root;        }        max(root->left);        max(root->right);    }    TreeNode * maxNode(TreeNode * root) {        // write your code here        if(root==NULL)            return NULL;        max(root);        return pmax;    }};



原创粉丝点击