注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
本帖最后由 zurich.hill 于 2020-8-24 22:45 编辑
为何19行这里,不是 left + right + 1 呢?
(不好意思,我已经看懂了,题目意思看错了。如果最长路径有4个node,他们的距离是 4 - 1 = 3 )
感谢各位~
- public class Solution {
-
- int max = 0;
-
- public int diameterOfBinaryTree(TreeNode root) {
-
- maxDepth(root);
-
- return max;
- }
-
- private int maxDepth(TreeNode root) {
-
- if (root == null) return 0;
-
- int left = maxDepth(root.left);
- int right = maxDepth(root.right);
-
- max = Math.max(max, left + right);
-
- return Math.max(left, right) + 1;
- }
- }
复制代码
|