前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LintCode Binary Tree Maximum Node二叉树的最大节点分析代码

LintCode Binary Tree Maximum Node二叉树的最大节点分析代码

作者头像
desperate633
发布2018-08-22 15:37:00
2380
发布2018-08-22 15:37:00
举报
文章被收录于专栏:desperate633

Find the maximum node in a binary tree, return the node.

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

代码语言:javascript
复制
 1

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

分析

简单的递归思路,不过注意为空的情况,所以最好将为空的点的值设为最小值

代码

代码语言:javascript
复制
public class Solution {
    /**
     * @param root the root of binary tree
     * @return the max ndoe
     */
    public TreeNode maxNode(TreeNode root) {
        if(root == null)
            return null;
        
        return getMaxNode(root);
    }
    
    public TreeNode getMaxNode(TreeNode root) {
        if(root == null)
            return new TreeNode(Integer.MIN_VALUE);
        
        TreeNode left = getMaxNode(root.left);
        TreeNode right = getMaxNode(root.right);
        
        if(root.val >= right.val && root.val >= left.val)
            return root;
        if(left.val >= right.val && left.val >= root.val)
            return left;
        return right;
    }    
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.04.02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档