LintCode二叉树的最大节点

本文介绍了一种在二叉树中寻找值最大的节点的方法。通过递归地遍历左右子树,比较每个节点的值来确定最大节点。提供了一个具体的实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本系列的博客将围绕在LintCode网站上的算法题进行编写,主要记录一下在刷题过程中的一些思路、想法,遇到困难时也会参考一些网上的资源。

目录


题目描述

在二叉树中寻找值最大的节点并返回。
样例:
            1
          /    \
        -5      2
      /  \     /   \
    0     3 -4    -5

解题思路

求解这个问题就像是求解一个数组的最大值一样,要将当前的最大的依次与后面的值进行比较,从而得到最大的值,唯一的不同的点就是这里使用的是树结构,所以要依次比较左右子树。

代码块

具体的实现代码如下:

public class Solution {
    /**
     * @param root the root of binary tree
     * @return the max ndoe
     */
    public TreeNode maxNode(TreeNode root) {
        // Write your code here
       if(root == null){
           return null;
       }
       TreeNode max = root;
       TreeNode temp;
       if(root.left == null && root.right == null){
           max = root;
       }
       if(root.left != null){
           temp = maxNode(root.left);
           if(max.val < temp.val){
               max = temp;
           }
       }
       if(root.right != null){
           temp = maxNode(root.right);
           if(max.val < temp.val){
               max = temp;
           }
       }
       return max;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值