給定一個二元樹,找出其最大深度。
二元樹的最大深度是從根節點到最遠葉節點的最長路徑上的節點數。
範例:
輸入: 二元樹 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
輸出: 3
這道題要求找到二元樹的最大深度,這個問題可以透過遞迴法或者深度優先搜尋(DFS)或者廣度優先搜尋(BFS)來解。
廣度優先搜尋 BFS 版本的話,就是每遍歷完一層的所有節點後,深度就加1。
實作:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr)
return 0;
queue<TreeNode*> q;
q.push(root);
int depth = 0;
// BFS
while (!q.empty()) {
int count = q.size(); // 當前這層的節點數量
// 處理當前這層的所有節點
for (int i = 0; i < count; i++) {
TreeNode* node = q.front();
q.pop();
if (node->left != nullptr) {
q.push(node->left);
}
if (node->right != nullptr) {
q.push(node->right);
}
}
depth++;
}
return depth;
}
};