mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2026-09-01 21:14:49 +08:00
add 543. Diameter of Binary Tree 🍺
This commit is contained in:
@@ -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;
|
||||
}
|
||||
};
|
||||
```
|
||||
Reference in New Issue
Block a user