您的位置:首页 > 其它

Lintcode:二叉树的最大节点

2017-12-05 12:25 363 查看
在二叉树中寻找值最大的节点并返回。

样例

给出如下一棵二叉树:
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->ri
9fd1
ght);
}
TreeNode * maxNode(TreeNode * root) {
// write your code here
if(root==NULL)
return NULL;
max(root);
return pmax;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: