diff --git a/README.md b/README.md index 935c495..c610aad 100644 --- a/README.md +++ b/README.md @@ -313,6 +313,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 500 |[Keyboard Row](https://leetcode.com/problems/keyboard-row)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/500.%20Keyboard%20Row.md)|Easy| | | 509 |[Fibonacci Number](https://leetcode.com/problems/fibonacci-number/)|[C++](solutions/509.%20Fibonacci%20Number.md)|Easy| | | 532 |[K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/532.%20K-diff%20Pairs%20in%20an%20Array.md)|Easy| | +| 543 |[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/)|[C++](solutions/543.%20Diameter%20of%20Binary%20Tree.md)|Easy| | | 561 |[Array Partition I](https://leetcode.com/problems/array-partition-i)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/561.%20Array%20Partition%20I.md)|Easy| | | 566 |[Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/566.%20Reshape%20the%20Matrix.md)|Easy| | | 572 |[Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)|[C++](solutions/572.%20Subtree%20of%20Another%20Tree.md)|Easy| | diff --git a/solutions/543. Diameter of Binary Tree.md b/solutions/543. Diameter of Binary Tree.md new file mode 100644 index 0000000..86ec05b --- /dev/null +++ b/solutions/543. Diameter of Binary Tree.md @@ -0,0 +1,28 @@ +# [543. Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) + +# 思路 + +求二叉树的直径,所谓直径就是两点之间的最远距离。对于树中的每个节点,我们都可以计算出经过该节点的两点间的最远距离(就等于其左子树的高加上右子树的高)。计算左右子树的高就是一个中序遍历。 + +时空复杂度均为O(n) + + +# C++ +``` C++ +class Solution { +private: + int res = 0; + int inorder(TreeNode *root){ + if(!root) return 0; + int l = inorder(root -> left); + int r = inorder(root -> right); + res = max(res, l + r); + return 1 + max(l, r); + } +public: + int diameterOfBinaryTree(TreeNode* root) { + inorder(root); + return res; + } +}; +``` \ No newline at end of file