【二叉树】【递归】Leetcode 543. 二叉树的直径

【二叉树】【递归】Leetcode 543. 二叉树的直径

---------------🎈🎈题目链接🎈🎈-------------------
在这里插入图片描述

解法1

class Solution {
    int result= 0;  // 定义一个全局变量result收获每一个节点为转折点的长度
    public int diameterOfBinaryTree(TreeNode root) {
        helper(root);
        return result;
    }

    public int helper(TreeNode root){
        if(root == null){
            return 0;
        }

        int left = helper(root.left); // 左边子树的深度
        int right = helper(root.right); // 右边子树的深度
        
        //全局变量result收获每一个节点为转折点的长度 = left(左边的深度)+right(右边的深度) 和之前的 选大的
        result = Math.max(result, left+right); 
        
        return Math.max(left,right)+1; //递归得到当前节点的深度
    }
}    

相关推荐

  1. leetcode543--直径

    2024-04-09 19:20:04       12 阅读
  2. 543. 直径

    2024-04-09 19:20:04       9 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-09 19:20:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-09 19:20:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-09 19:20:04       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-09 19:20:04       20 阅读

热门阅读

  1. 【Linux】编写一个 shell 脚本&执行

    2024-04-09 19:20:04       14 阅读
  2. 深入了解Fcgiwrap:使CGI脚本与Nginx无缝集成

    2024-04-09 19:20:04       17 阅读
  3. 【蓝桥杯】赛前一周模板

    2024-04-09 19:20:04       14 阅读
  4. ChatGPT新手指南:如何用AI写出专业学术论文

    2024-04-09 19:20:04       12 阅读
  5. vue3 reactive包裹数组无法页面无法响应式

    2024-04-09 19:20:04       12 阅读
  6. 定制您的设备体验:如何更改Android启动动画

    2024-04-09 19:20:04       14 阅读
  7. 出海的网络挑战

    2024-04-09 19:20:04       13 阅读
  8. ALTER TABLE 之 慢速变更(slow alter)

    2024-04-09 19:20:04       15 阅读
  9. LeetCode 670. 最大交换

    2024-04-09 19:20:04       14 阅读
  10. memset()函数及其作用

    2024-04-09 19:20:04       19 阅读