拍头一想,前两道题昨天不是已经做完了吗,今天真轻松啊
没什么好说的,前2道题都是遍历计数
题目链接:104. 二叉树的最大深度 - 力扣(LeetCode)
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode *> que;
if(root) que.push(root);
int depth=0;
while(!que.empty()){
int size=que.size();
depth++;
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);
}
}
return depth;
}
};
题目链接:111. 二叉树的最小深度 - 力扣(LeetCode)
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode *> que;
if(root) que.push(root);
int depth=0;
while(!que.empty()){
int size=que.size();
depth++;
for(int i=0;i<size;i++){
TreeNode *node=que.front();
que.pop();
if(!node->left&&!node->right) return depth;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return depth;
}
};
题目链接:222. 完全二叉树的节点个数 - 力扣(LeetCode)
// class Solution
// {
// public:
// int countNodes(TreeNode *root)
// {
// queue<TreeNode*> que;
// int cnt=0;
// if(root) que.push(root);
// while(!que.empty()){
// int size=que.size();
// for(int i=0;i<size;i++){
// TreeNode *node=que.front();
// que.pop();
// cnt++;
// if(node->left) que.push(node->left);
// if(node->right) que.push(node->right);
// }
// }
// return cnt;
// }
// };
// class Solution
// {
// public:
// int countNodes(TreeNode *root)
// {
// stack<TreeNode*> st;
// int cnt=0;
// if(root) st.push(root);
// while(!st.empty()){
// TreeNode *node=st.top();
// st.pop();
// cnt++;
// if(node->right) st.push(node->right);
// if(node->left) st.push(node->left);
// }
// return cnt;
// }
// };
class Solution // 递归找满二叉树
{
public:
int countNodes(TreeNode *root)
{
if (!root)
return 0;
int leftDepth = 1;
int rightDepth = 1;
TreeNode *left = root->left;
TreeNode *right = root->right;
while (left)
{
left = left->left;
leftDepth++;
}
while (right)
{
right = right->right;
rightDepth++;
}
if (leftDepth == rightDepth)
return (2 << (leftDepth - 1)) - 1;
return countNodes(root->left)+countNodes(root->right)+1;
}
};
思路
第一时间是想到遍历计数,但是满足不了进阶要求的时间复杂度小于o(n)
解题方法
深度优先和广度优先都是o(n)。只能另寻他法。
这时候想到完全二叉树的特性,如果是满二叉树的话,结点数直接等于2^n-1。
所以只要计算最左和最右子树的长度,如果判断是满二叉树的话就直接等于2^n-1。如果不是那就再往下找,这时候就是递归发挥作用的时候了.
递归三步走,
1.确定参数和返回值,我们要找满二叉树,那只需要一个结点发散下去就行,那么参数是TreeNode *root,返回int的节点数
2.确定递归出口,我们要找满二叉树,那判断条件自然是leftDepth==rightDepth
3.确定单层递归的执行逻辑,那么就是
int leftNum = getNodesNum(cur->left); // 左
int rightNum = getNodesNum(cur->right); // 右
int treeNum = leftNum + rightNum + 1; // 中
return treeNum;
往最左和最有一直深入下去,直到出口
复杂度
时间复杂度:
O(logn∗logn)
空间复杂度:
O(logn)