牛客题霸-二叉树最大深度题解
bfs求二叉树最大深度
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
typedef struct{
TreeNode* val;
int h;//记录当前结点在第几层//
}node;
int maxDepth(TreeNode* root) {
// write code here
if(root==NULL)return 0;
queue<node>q;
int h;
q.push({root,1});
while(!q.empty()){
node LNode=q.front();
q.pop();
TreeNode* top=LNode.val;
h=LNode.h;
if(top->left!=NULL){
node next;
next.val=top->left;
next.h=h+1;//左子树层数等于父结点层数加一//
q.push(next);
}
if(top->right!=NULL){
node next;
next.val=top->right;
next.h=h+1;//右子树层数等于父结点层数加一//
q.push(next);
}
}
return h;//最后出队的结点就是最深结点//
}
};