LeetCode Hot100 | Day1 | 二叉树:二叉树的直径

LeetCode Hot100 | Day1 | 二叉树:二叉树的直径

主要学习内容:

二叉树深度求法

深度的 left+right+1 得到的是从根结点到叶子结点的节点数量

543.二叉树的直径

[543. 二叉树的直径 - 力扣(LeetCode)](https://leetcode.cn/problems/diameter-of-binary-tree/description/?envType=problem-list-v2&envId=2cktkvj&difficulty=EASY)\](https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/description/) ##### 解法思路: 说之前先来看一种经典的错误。。 ```c++ class Solution { public: int maxDepth=-1; int tra(TreeNode *t) { if(t==nullptr) return 0; return 1+max(tra(t->left),tra(t->right)); } int diameterOfBinaryTree(TreeNode* root) { if(root==nullptr) return 0; return tra(root->left)+tra(root->right); } }; ``` 哈哈想的是,左右子树最大深度求出来一加,直接完事了,可惜的是这种是错误的 ![image-20241005162425862](https://img-blog.csdnimg.cn/img_convert/a1bbcb76967e510529b7b406aa0520d2.png) 这个是错误示例,很明显,最长的直径在右子树上,而不是左子树加右子树的深度。 不过这也启发我们,说明思路是对的,只是应该有一个记录最大值的变量,然后对每一个节点都进行一遍这个操作,把最大的记录下来就是了 那接下来就是二叉树求深度 **1.函数参数和返回值** ```c++ int maxDepth=-1; int tra(TreeNode *t) ``` maxDepth记录最大直径,就是答案 返回值返回以当前结点为根结点的子树的深度 **2.终止条件** 直到没有数即没有结点要构建就是结束 ```c++ if(t==nullptr) return 0; ``` 碰到空了不加深度,直接返回0就行 **3.本层代码逻辑** ```c++ int left=tra(t->left); int right=tra(t->right); maxDepth=max(maxDepth,left+right+1); return 1+max(left,right); ``` left记录左子树深度 right记录右子树深度 更新以当前结点为子树的深度(l+r+1)和maxDepth之间的大小,最大值赋值给maxDepth 更新后,返回上层递归函数当前子树的最大深度 **完整代码:** ```c++ class Solution { public: int maxDepth=-1; int tra(TreeNode *t) { if(t==nullptr) return 0; int left=tra(t->left); int right=tra(t->right); maxDepth=max(maxDepth,left+right+1); return 1+max(left,right); } int diameterOfBinaryTree(TreeNode* root) { if(root==nullptr) return 0; int t=tra(root); return maxDepth-1; } }; ``` 最后注意:我们求的直径是边数,(l+r+1求的是节点数),要减去1才是边数。

相关推荐
啊阿狸不会拉杆1 小时前
《机器学习导论》第 7 章-聚类
数据结构·人工智能·python·算法·机器学习·数据挖掘·聚类
木非哲1 小时前
机器学习--从“三个臭皮匠”到 XGBoost:揭秘 Boosting 算法的“填坑”艺术
算法·机器学习·boosting
MSTcheng.1 小时前
CANN ops-math算子的跨平台适配与硬件抽象层设计
c++·mfc
code monkey.1 小时前
【Linux之旅】Linux 进程间通信(IPC)全解析:从管道到共享内存,吃透进程协作核心
linux·c++·ipc
薛定谔的猫喵喵2 小时前
基于C++ Qt的唐代诗歌查询系统设计与实现
c++·qt·sqlite
Re.不晚2 小时前
JAVA进阶之路——数据结构之线性表(顺序表、链表)
java·数据结构·链表
小辉同志2 小时前
437. 路径总和 III
算法·深度优先·广度优先
阿昭L2 小时前
C++异常处理机制反汇编(三):32位下的异常结构分析
c++·windows·逆向工程
匆匆那年9672 小时前
llamafactory推理消除模型的随机性
linux·服务器·学习·ubuntu
Cinema KI2 小时前
C++11(下) 入门三部曲终章(基础篇):夯实语法,解锁基础编程能力
开发语言·c++