leetcode 543. Diameter of Binary Tree 最长树的片段 + 深度优先遍历DFS

待我称王封你为后i 2022-06-03 03:41 225阅读 0赞

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

本题很简单就是在二叉树中寻找最长的片段,直接深度优先遍历即可

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. using namespace std;
  16. /*
  17. struct TreeNode
  18. {
  19. int val;
  20. TreeNode *left;
  21. TreeNode *right;
  22. TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  23. };
  24. */
  25. class Solution
  26. {
  27. public:
  28. int diameterOfBinaryTree(TreeNode* root)
  29. {
  30. int res = 0;
  31. maxDepth(root, res);
  32. return res;
  33. }
  34. int maxDepth(TreeNode* root, int& res)
  35. {
  36. if (root == NULL)
  37. return 0;
  38. else
  39. {
  40. int left = maxDepth(root->left,res);
  41. int right = maxDepth(root->right,res);
  42. res = max(res, left + right);
  43. return max(left, right) + 1;
  44. }
  45. }
  46. };

发表评论

表情:
评论列表 (有 0 条评论,225人围观)

还没有评论,来说两句吧...

相关阅读