题解 | #二叉树的深度#
二叉树的深度
https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
lass Solution {
public:
int TreeDepth(TreeNode* pRoot) {
queue<TreeNode*> myqueue;
vector<int> nodenumber={0};
if (pRoot==NULL) return 0;
else {
myqueue.push(pRoot);
nodenumber[1]=1;
}
int k=1;//从第一层开始
bool havelevel=true;//此层有节点
while(havelevel==true){
int havenextlevel=0;
for(int i=1;i<=nodenumber[k];i++){//遍历每一层的所有节点
if(!myqueue.empty()){
TreeNode *first=myqueue.front();
if(first->left!=NULL){
myqueue.push(first->left);
nodenumber[k+1]++;
havenextlevel=1;
}
if(first->right!=NULL){
myqueue.push(first->right);
nodenumber[k+1]++;
havenextlevel=1;
}
myqueue.pop();
}
}
if(havenextlevel==0){
havelevel=false;
}
else{
k++;
}
}
return k;
}
};
public:
int TreeDepth(TreeNode* pRoot) {
queue<TreeNode*> myqueue;
vector<int> nodenumber={0};
if (pRoot==NULL) return 0;
else {
myqueue.push(pRoot);
nodenumber[1]=1;
}
int k=1;//从第一层开始
bool havelevel=true;//此层有节点
while(havelevel==true){
int havenextlevel=0;
for(int i=1;i<=nodenumber[k];i++){//遍历每一层的所有节点
if(!myqueue.empty()){
TreeNode *first=myqueue.front();
if(first->left!=NULL){
myqueue.push(first->left);
nodenumber[k+1]++;
havenextlevel=1;
}
if(first->right!=NULL){
myqueue.push(first->right);
nodenumber[k+1]++;
havenextlevel=1;
}
myqueue.pop();
}
}
if(havenextlevel==0){
havelevel=false;
}
else{
k++;
}
}
return k;
}
};