利用广度优先遍历的思路,但是一次遍历完在上一层加入的所有节点
#includeclass Solution { public: int maxDepth(TreeNode* root) { if(root==nullptr) { return 0; } queue q; TreeNode * temp=root; int count=0;//层数 q.push(temp); int i=0; while(!q.empty()){ i=q.size();//用来标记上一层加入到队列的新节点个数 while(i>0){//这层循环用来保证遍历完上层加入的所有节点 temp=q.front();//取首元素 if(temp->left!=nullptr){ q.push(temp->left); } if(temp->right!=nullptr){ q.push(temp->right); } q.pop(); i--; } count++;//遍历完上一层加入的所有节点后,层数加1 } return count; } };



