### 思路
1. **构建二叉树**:
- 使用输入数据构建二叉树。
- 使用一个数组或哈希表来存储每个节点的子节点。
2. **计算直径**:
- 使用深度优先搜索(DFS)计算每个节点的深度。
- 计算每个节点的左子树和右子树的深度之和,更新最大直径。
### 伪代码
```
function buildTree(n, edges):
create an array of TreeNode of size n+1
for each edge (x, y) in edges:
if x does not have a left child:
set x's left child to y
else:
set x's right child to y
return root (TreeNode[1])
function diameterOfBinaryTree(root):
maxDiameter = 0
function depth(node):
if node is null:
return 0
leftDepth = depth(node.left)
rightDepth = depth(node.right)
maxDiameter = max(maxDiameter, leftDepth + rightDepth)
return max(leftDepth, rightDepth) + 1
depth(root)
return maxDiameter
n = input()
edges = []
for i = 1 to n-1:
x, y = input()
edges.append((x, y))
root = buildTree(n, edges)
print(diameterOfBinaryTree(root))
```
### C++代码
#include <iostream>
#include <vector>
#include <algorithm>using namespace std;struct TreeNode {int val;TreeNode* left;TreeNode* right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};TreeNode* buildTree(int n, const vector<pair<int, int>>& edges) {vector<TreeNode*> nodes(n + 1, nullptr);for (int i = 1; i <= n; ++i) {nodes[i] = new TreeNode(i);}for (const auto& edge : edges) {int x = edge.first, y = edge.second;if (!nodes[x]->left) {nodes[x]->left = nodes[y];} else {nodes[x]->right = nodes[y];}}return nodes[1];
}int maxDiameter = 0;int depth(TreeNode* node) {if (!node) return 0;int leftDepth = depth(node->left);int rightDepth = depth(node->right);maxDiameter = max(maxDiameter, leftDepth + rightDepth);return max(leftDepth, rightDepth) + 1;
}int diameterOfBinaryTree(TreeNode* root) {depth(root);return maxDiameter;
}int main() {int n;cin >> n;vector<pair<int, int>> edges(n - 1);for (int i = 0; i < n - 1; ++i) {int x, y;cin >> x >> y;edges[i] = {x, y};}TreeNode* root = buildTree(n, edges);cout << diameterOfBinaryTree(root) << endl;return 0;
}
### 总结
1. **构建树**:通过输入数据构建二叉树。
2. **计算直径**:使用DFS计算每个节点的深度,并更新最大直径。
3. **时间复杂度**:O(n),其中n是节点数。