葉林
Linked with GitHub
# LeetCode - 0543. Diameter of Binary Tree ### 題目網址:https://leetcode.com/problems/diameter-of-binary-tree/ ###### tags: `LeetCode` `Easy` `動態規劃(Dynamic Programming)` `圖論` ```cpp= /* -LeetCode format- Problem: 543. Diameter of Binary Tree Difficulty: Easy by Inversionpeter */ /** * 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 { int diameter = 0; int Depths(TreeNode *node) { if (!node) return 0; int left = Depths(node->left), right = Depths(node->right); diameter = max(diameter, left + right); return max(left, right) + 1; } public: int diameterOfBinaryTree(TreeNode* root) { Depths(root); return diameter; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up