来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree

描述

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

示例 :
给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

题解

算法

  • 计算当前node左右节点的深度,然后可得到此路径上node的个数 (depth of node.left) + (depth of node.right) + 1
  • 搜索每个节点并记录路径上node个数的最大值
  • 由于两结点之间的路径长度是以它们之间的数目表示,故最终结果需将node数 - 1
  1. class Solution {
  2. int nodeAmount;
  3. public int diameterOfBinaryTree(TreeNode root) {
  4. nodeAmount = 1;
  5. depth(root);
  6. return nodeAmount - 1;
  7. }
  8. public int depth(TreeNode node) {
  9. if (null == node) return 0;
  10. int L = depth(node.left);
  11. int R = depth(node.right);
  12. nodeAmount = Math.max(nodeAmount, L + R + 1);
  13. return Math.max(L, R) + 1;
  14. }
  15. }

复杂度分析

  • 时间复杂度:O(N),每个节点只访问一次。
  • 空间复杂度:O(N),深度优先搜索的栈开销。