給定一棵二叉樹,求其最大深度。最大深度是從根節點到最遠葉子節點的最長路徑上的節點數。
最直觀的方法:樹的最大深度 = max(左子樹深度, 右子樹深度) + 1。
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return 1 + max(left, right);
}
};
用隊列逐層遍歷,計數層數。
int maxDepth(TreeNode* root) {
if (!root) return 0;
queue q;
q.push(root);
int depth = 0;
while (!q.empty()) {
int sz = q.size();
depth++;
while (sz--) {
TreeNode* node = q.front(); q.pop();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return depth;
}
棧存 (節點, 當前深度),模擬遞歸。
int maxDepth(TreeNode* root) {
if (!root) return 0;
stack> st;
st.push({root, 1});
int ans = 0;
while (!st.empty()) {
auto [node, d] = st.top(); st.pop();
ans = max(ans, d);
if (node->left) st.push({node->left, d+1});
if (node->right) st.push({node->right, d+1});
}
return ans;
}
| 方法 | 時間 | 空間 | 備註 |
|---|---|---|---|
| 遞歸 DFS | O(n) | O(h) | h 為樹高,最壞 O(n),可能棧溢出 |
| BFS 隊列 | O(n) | O(w) | w 為最大層寬度,最壞 O(n) |
| 顯式棧 DFS | O(n) | O(h) | 手動控制棧,避免系統棧溢出 |