mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
28 lines
780 B
Markdown
28 lines
780 B
Markdown
![]() |
# [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;
|
||
|
}
|
||
|
};
|
||
|
```
|