AcWing 71. 二叉树的深度 BFS
原题链接
简单
作者:
upupgo
,
2021-04-16 19:55:12
,
所有人可见
,
阅读 390
BFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int treeDepth(TreeNode* root) {
if (!root) return 0;
// bfs
queue<TreeNode*> q;
q.push(root);
int cnt = 0;
while (!q.empty()) {
int count = q.size(); // 当前层大小
while (count--) {
auto t = q.front();
q.pop();
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
cnt++;
}
return cnt;
}
};