104. 二叉树的最大深度:
111. 二叉树的最小深度:
222. 完全二叉树的节点个数:力扣
前序遍历和后序遍历都可以,前序求的是深度,后序求的是高度。
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始)
递归三部曲
用后序遍历(左右中)来计算树的高度。
1. 确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。
代码如下:
int getdepth(treenode* node)
2. 确定终止条件:如果为空节点的话,就返回0,表示高度为0。
代码如下:
if (node == NULL) return 0;
3. 确定单层递归的逻辑:先求它的左子树的深度,再求右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。
代码如下:
int leftdepth = getdepth(node->left); // 左
int rightdepth = getdepth(node->right); // 右
int depth = 1 + max(leftdepth, rightdepth); // 中
return depth;
104. 二叉树的最大深度
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> q;
if(root != nullptr) q.push(root);
int res = 0;
while(!q.empty()){
res++;
int size = q.size();
for(int i = 0; i < size; i++){
auto n = q.front();
q.pop();
if(n->left != nullptr) q.push(n->left);
if(n->right != nullptr) q.push(n->right);
}
}
return res;
}
};
111. 二叉树的最小深度
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> q;
if(root != nullptr) q.push(root);
int res = 0;
while(!q.empty()){
res++;
int size = q.size();
for(int i = 0; i < size; i++){
auto n = q.front();
q.pop();
if(n->left == nullptr && n->right == nullptr){ // 没有孩子节点的为叶子节点
q=queue<TreeNode*>(); // 清空队列,以便跳出两层循环
break;
}
if(n->left != nullptr) q.push(n->left);
if(n->right != nullptr) q.push(n->right);
}
}
return res;
}
};
222. 完全二叉树的节点个数
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> q;
TreeNode* n;
if(root != nullptr) q.push(root);
int num = 0;
while(!q.empty()){
n = q.front();
q.pop();
num++;
if(n->left != nullptr) q.push(n->left);
if(n->right != nullptr) q.push(n->right);
}
return num;
}
};
解法二:二分
(TODO)
题解:力扣