题目描述

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

示例

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


解题思路

解法1,计算穿过root,root的左孩子,root的右孩子的直径比较

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int calc_depth(TreeNode* root, int count) {
  13. if (root == NULL)
  14. return count-1;
  15. return max(calc_depth(root->left, count+1), calc_depth(root->right, count+1));
  16. }
  17. int diameterOfBinaryTree(TreeNode* root) {
  18. if (root==NULL)
  19. return 0;
  20. int depth_root = calc_depth(root->left, 1) + calc_depth(root->right, 1);
  21. int depth_left = diameterOfBinaryTree(root->left);
  22. int depth_right = diameterOfBinaryTree(root->right);
  23. return max(depth_root, max(depth_left, depth_right));
  24. }
  25. };

解法2,在计算depth的过程中便开始记录

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int res=0;
  13. int calc_depth(TreeNode* root, int count) {
  14. if (root == NULL)
  15. return 0;
  16. int l = calc_depth(root->left, count+1);
  17. int r = calc_depth(root->right, count+1);
  18. res = max(res, l+r+1);
  19. return max(l, r)+1;
  20. }
  21. int diameterOfBinaryTree(TreeNode* root) {
  22. if (root==NULL)
  23. return 0;
  24. calc_depth(root, 1);
  25. return res-1;
  26. }
  27. };