1

#yyds干货盘点# leetcode算法题:二叉树的直径

 1 year ago
source link: https://blog.51cto.com/u_13321676/5608468
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# leetcode算法题:二叉树的直径

精选 原创

灰太狼_cxh 2022-08-22 14:30:55 博主文章分类:leetcode ©著作权

文章标签 子树 二叉树 结点 文章分类 Java 编程语言 阅读数210

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。

给定二叉树

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

代码实现:

class Solution {
int ans;
public int diameterOfBinaryTree(TreeNode root) {
ans = 1;
depth(root);
return ans - 1;
}
public int depth(TreeNode node) {
if (node == null) {
return 0; // 访问到空节点了,返回0
}
int L = depth(node.left); // 左儿子为根的子树的深度
int R = depth(node.right); // 右儿子为根的子树的深度
ans = Math.max(ans, L+R+1); // 计算d_node即L+R+1 并更新ans
return Math.max(L, R) + 1; // 返回该节点为根的子树的深度
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK