题解 | #二叉树的最大深度#
二叉树的最大深度
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) {} * }; */ #include <queue> class Solution { public: // 层序遍历 void treeTrave(int& depth, TreeNode* root) { queue<TreeNode*> fatherNodes, childNodes; fatherNodes.push(root); depth = 1; while (!fatherNodes.empty()) { auto node = fatherNodes.front(); if (node->left != nullptr) { childNodes.push(node->left); } if (node->right != nullptr) { childNodes.push(node->right); } fatherNodes.pop(); if (fatherNodes.empty() && !childNodes.empty()) { while (!childNodes.empty()) { fatherNodes.push(childNodes.front()); childNodes.pop(); } depth++; } else if (fatherNodes.empty() && childNodes.empty()) { break; } } } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ int maxDepth(TreeNode* root) { // write code here if (root == nullptr) { return 0; } int depth = 0; treeTrave(depth, root); return depth; } };
在线编程练习 文章被收录于专栏
C++在线编程练习题解