mysql查詢今天、昨天、7天、近30天、本月、上一月 資料
阿新 • • 發佈:2022-05-16
543. 二叉樹的直徑
給定一棵二叉樹,你需要計算它的直徑長度。一棵二叉樹的直徑長度是任意兩個結點路徑長度中的最大值。這條路徑可能穿過也可能不穿過根結點。
示例 :
給定二叉樹1
/ \
2 3
/ \
4 5
返回 3, 它的長度是路徑 [4,2,1,3] 或者 [5,2,1,3]。注意:兩結點之間的路徑長度是以它們之間邊的數目表示。
程式碼實現:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int diameterOfBinaryTree(TreeNode* root) { int res = 0; help(root, res); return res; } int help(TreeNode*root, int &res) { if(!root) return 0; int l = help(root->left, res); int r = help(root->right, res); res = max(res, r +l); return max(l, r) + 1; } };