leetcode104题
int maxDepth(TreeNode* root) {
if(root==nullptr){
return 0;
}
/
queue<TreeNode *> q;
q.push(root);
int ans=0;
while(!q.empty()){
//拿到当前层次的节点个数
int size=q.size();
//进行层次遍历
while(size>0){
TreeNode* node=q.front();q.pop();
if(node->left){q.push(node->left);};
if(node->right){q.push(node->right);};
size--;
}
//遍历一层就加一
ans++;
}
return ans;
}
leetcode110题
int height(TreeNode *root){
if(root==nullptr){
return 0;
}
//获取左子树的高度
int leftHeight=height(root->left);
//获取右子树的高度
int rightHeight=height(root->right);
//如果左子树或右子树的高度为-1,或者左右子树的高度差大于1,说明不是平衡二叉树,返回-1
if(leftHeight==-1||rightHeight==-1|| fabs(leftHeight-rightHeight)>1){
return -1;
}else{
//返回左子树和右子树中较大的高度,并加上根节点的高度1
return max(leftHeight,rightHeight)+1;
}
}
bool isBalanced(TreeNode* root) {
return height(root)>=0;
}
leetcode111题
int minDepth(TreeNode* root) {
if(root==nullptr){
return 0;
}
queue<pair<TreeNode *, int> > q;
//将根节点和深度1加入队列
q.emplace(root,1);
//队列不为空开始循环
while(!q.empty()){
//拿到队列头部的节点指针
TreeNode *node=q.front().first;
//拿到队列的深度
int path=q.front().second;
//弹出头部元素
q.pop();
//当左右节点都为空说明为叶子节点
if(node->left==nullptr&&node->right==nullptr){
//返回叶子节点的深度
return path;
}
//如果当前节点有左子节点
if(node->left!=nullptr){
//将下一个左子节点和深度加1添加到队列中
q.emplace(node->left,path+1);
}
//如果当前节点有右子节点
if(node->right!=nullptr){
//将下一个右子节点和深度加1添加到队列中
q.emplace(node->right,path+1);
}
}
//树为空树返回0
return 0;
}
总结
二叉树的最大深度只要判断二叉树为空和不为空俩种情况,二叉树为空最大深度为0,二叉树不为空,最大深度等于左子树的最大深度和右子树的最大深度取最大值加1
平衡树是指左右子树的高度差不超过1的二叉树,
- .当二叉树为空,则是平衡二叉树。
- 2.判断左右子树的高度是否超过1,超过则不是平衡二叉树,
- 3.继续递归判断左右子树是否是平衡树。
二叉树的最小深度
- 当二叉树为空,最小深度为0
- 如果二叉树的左子树为空,但右子树不为空,则最小深度为右子树的最小深度加1。
- 如果二叉树的右子树为空,但左子树不为空,则最小深度为左子树的最小深度加1。
- 否则,最小深度等于左子树的最小深度和右子树的最小深度中的较小值加1。