543. 二叉树的直径
知识点
不同教材有差异,按照这个理解:层数从0开始,也就是根结点是第0层,树的深度=高度,都是最大层数
问题描述
给你一棵二叉树的根节点,返回该树的 直径 。
二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。
两节点之间路径的 长度 由它们之间边数表示。
分析
用该题初步理解树形DP
法一、递归
class Solution {
public:
int res = 0;
int solve(TreeNode* root) {
int x = 0, y = 0;
if (root == nullptr) {
return 0;
}
x = solve(root->left);
y = solve(root->right);
res = max(res, x+y);
return max(x, y)+1;
}
int diameterOfBinaryTree(TreeNode* root) {
solve(root);
return res;
}
};
其中return max(x, y)+1
中的+1也可以写到上边的x和y中,即:
class Solution {
public:
int res = 0;
int solve(TreeNode* root) {
int x = 0, y = 0;
if (root == nullptr) {
return 0;
}
x = solve(root->left) + 1;
y = solve(root->right) + 1;
res = max(res, x+y-2);
return max(x, y);
}
int diameterOfBinaryTree(TreeNode* root) {
solve(root);
return res;
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】