题目描述
我的思路很简单,就是简单的bfs算法,每次遍历完当前一层的节点,顺带将下一层的非nullptr节点加进来。循环截止的出口是队列为空。
算法1
(bfs) $O(n)$
C++ 代码
/**
* 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) {
queue<TreeNode*> q;
int depth = 0;
if(!root) return 0;
q.push(root);
while(q.size())
{
depth++;
int n = q.size();
for(int i = 0; i < n; i ++ )
{
TreeNode* t = q.front();
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return depth;
}
};