当前位置: 首页 > news >正文

【力扣 - 二叉树的直径】

题目描述

给你一棵二叉树的根节点,返回该树的 直径 。
二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。
两节点之间路径的 长度 由它们之间边数表示。
在这里插入图片描述

提示:

树中节点数目在范围 [1, 10000]

-100 <= Node.val <= 100

题解

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
int maxLen(struct TreeNode* root)
{if(root == NULL){return 0; // Base case: return 0 if the current node is NULL}int leftLen;int rightLen;// Calculate the maximum path length of the left subtreeleftLen = maxLen(root->left) + 1;// Calculate the maximum path length of the right subtreerightLen = maxLen(root->right) + 1;// Return the maximum of the left and right path lengthsreturn leftLen > rightLen ? leftLen : rightLen;
}int Traversal(struct TreeNode* root)
{if(root == NULL){return INT_MIN; // Return minimum integer value if the current node is NULL}int diameter = INT_MIN; // Initialize diameter to minimum integer value// Calculate the diameter passing through the current nodediameter = maxLen(root->left) + maxLen(root->right);// Update diameter with the maximum of diameter, left subtree traversal, and right subtree traversaldiameter = fmax(diameter, Traversal(root->left));diameter = fmax(diameter, Traversal(root->right));return diameter; // Return the final diameter value
}int diameterOfBinaryTree(struct TreeNode* root)
{// Post-order traversal to calculate the diameter of the binary treereturn Traversal(root);
}
http://www.lryc.cn/news/304174.html

相关文章:

  • 大数据,对于生活的改变
  • py2neo和neo4j
  • 解决windows无法访问wsl下docker服务
  • OpenAI划时代大模型——文本生成视频模型Sora作品欣赏(二)
  • Python第十九章(模块)
  • 【Linux网络编程五】Tcp套接字编程(四个版本服务器编写)
  • APP 有漏洞被测要下架,怎么处理?
  • 2024年2月19日-2月25日(全面进行+收集免费虚幻商城资源)
  • Flutter学习4 - Dart数据类型
  • leetcode hot100单词拆分
  • 大数据构建知识图谱:从技术到实战的完整指南
  • WebServer -- 定时器处理非活动连接(上)
  • 微服务部署:金丝雀发布、蓝绿发布和滚动发布的对比
  • 轻松入门MySQL:优化复杂查询,使用临时表简化数据库查询流程(13)
  • vmware的ubuntu虚拟机因空间满无法启动
  • Unity数据持久化之PlayerPrefs
  • uniapp微信公众号H5分享
  • 深入理解指针(c语言)
  • 高级语言期末2015级唐班B卷
  • 开发一款招聘小程序需要具备哪些功能?
  • 嵌入式学习-qt-Day3
  • 零基础到高级:Android音视频开发技能路径规划
  • 阿里云香港轻量应用服务器网络线路cn2?
  • python中websockets与主线程传递参数
  • js谐音梗创意小游戏《望子成龙》
  • 第十篇:node处理404和服务器错误
  • 左右互博。
  • android通过广播打印ram使用信息
  • 内存管理——线性内存,进程空间
  • 入门Python必读的流程控制语句