classSolution{public:intmaxDepth(TreeNode* root){if(!root)return0;
queue<TreeNode*> q;
q.push(root);int depth =0;while(!q.empty()){int size = q.size();
depth ++;for(int i =0; i < size; i ++){auto a = q.front();
q.pop();if(a->left) q.push(a->left);if(a->right) q.push(a->right);}}return depth;}};
559. N 叉树的最大深度
思路
递归:同上,只不过这次所有孩子都要比较
迭代:同上,只不过每次都要放入多个孩子都队列里
代码
递归
classSolution{public:intmaxDepth(Node* root){if(root ==nullptr)return0;int res =0;for(auto a:root->children){
res =max(res,maxDepth(a));}return res +1;}};
迭代
classSolution{public:intmaxDepth(Node* root){if(!root)return0;
queue<Node*> q;
q.push(root);int depth =0;while(!q.empty()){int size = q.size();
depth ++;for(int i =0; i < size; i ++){auto a = q.front();
q.pop();for(int j =0; j < a->children.size(); j ++)if(a->children[j]) q.push(a->children[j]);}}return depth;}};
classSolution{public:intcountNodes(TreeNode* root){if(!root)return0;int left =countNodes(root->left);int right =countNodes(root->right);return left + right +1;}};
迭代
classSolution{public:intcountNodes(TreeNode* root){if(!root)return0;
queue<TreeNode*> q;
q.push(root);int res =0;while(!q.empty()){int size = q.size();for(int i =0; i < size; i ++){auto a = q.front();
q.pop();
res ++;if(a->left) q.push(a->left);if(a->right) q.push(a->right);}}return res;}};
完全二叉树性质
classSolution{public:intcountNodes(TreeNode* root){if(root ==nullptr)return0;
TreeNode* left = root->left;
TreeNode* right = root->right;int a =0, b =0;while(left){
left = left->left;
a ++;}while(right){
right = right->right;
b ++;}if(a == b){return(2<< a)-1;}returncountNodes(root->left)+countNodes(root->right)+1;}};