104.二叉树的最大深度
深度:从根节点到叶子节点(**使用前序(中左右)**从上到下,取决于深度从0还是1开始)
高度:从叶子节点到根节点(**使用后序(左右中)**从下到上,取决于高度从0还是1开始)
根节点的高度=二叉树的最大深度
使用层序遍历,求深度
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) return 0; //数组为空的情况
queue<TreeNode*> que;
int depth=0;
if(root!=NULL) que.push(root);
while(!que.empty()){
int size=que.size();
depth++;
while(size--){
TreeNode* node=que.front();
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return depth;
}
};
使用后序(左右中)来计算树的高度
中间的处理过程返回给父节点,父节点就知道孩子的高度,再+1,就是二叉树的高度
递归三部曲:
确定递归函数的参数和返回值,参数传入的是树的根节点,返回值是int类型
确定终止条件:如果为空节点,就返回0,表示高度是0
确定单层递归的逻辑:先求它的左子树深度,再求右子树深度,最后取左右子树最大的数组再+1(+1是要计算上当前父节点)
lass Solution {
public:
int getdepth(TreeNode* node){
if(node==NULL) return 0;
int leftdepth=getdepth(node->left);
int rightdepth=getdepth(node->right);
int depth=1+max(leftdepth,rightdepth);
return depth;
}
int maxDepth(TreeNode* root) {
return getdepth(root);
}
};
111.二叉树的最小深度
最小深度:从根节点到最近叶子节点的最短路径上的节点数量
叶子节点:左右孩子都为空的节点
1.使用层序遍历
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0; //数组为空的情况
queue<TreeNode*> que;
int depth=0;
if(root!=NULL) que.push(root);
while(!que.empty()){
int size=que.size();
depth++;
while(size--){
TreeNode* node=que.front();
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
if(!node->left && !node->right){ //当左右孩子都为空时 说明是最低点
return depth;
}
}
}
return depth;
}
};
2.使用后序遍历
class Solution {
public:
int getdepth(TreeNode* node){
if(node==NULL)return 0;
int leftdepth=getdepth(node->left);
int rightdepth=getdepth(node->right);
//当左子树为空 右不为空 不是最低点
if(node->left==NULL && node->right!=NULL){
return 1+rightdepth;
}
//左子树不为空 右子树为空 不是最低点
if(node->left!=NULL && node->right==NULL){
return 1+leftdepth;
}
int result=1+min(leftdepth,rightdepth);
return result;
}
int minDepth(TreeNode* root) {
return getdepth(root);
}
};
222.完全二叉树的节点个数
使用后序遍历,在递归左右之后,遍历中时做出操作
class Solution {
public:
int getnum(TreeNode* node){
if(node==NULL)return 0;
int leftnum=getnum(node->left); //左
int rightnum=getnum(node->right); //右
int treenum=leftnum+rightnum+1; //遍历中时处理数量
return treenum;
}
int countNodes(TreeNode* root) {
return getnum(root);
}
};