题解 | #二叉树的最大深度#
二叉树的最大深度
https://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ // int search(TreeNode* cur){ // if(cur==nullptr)return 0; // int left=search(cur->left); // int right=search(cur->right); // return max(left,right)+1; // } int maxDepth(TreeNode* root) { // // write code here // int result=search(root); // return result; // } queue<TreeNode*>que; if(root==nullptr)return 0; que.push(root); int count=0; while(!que.empty()){ int size=que.size(); for(int i=0;i<size;i++){ TreeNode* node=que.front(); que.pop(); if(node->left)que.push(node->left); if(node->right)que.push(node->right); } count++; } return count; } };
层序遍历的解题思路
建立队列
用while+for循环把每一层节点都推入队列里