个人学习记录
110.平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
提示:
树中的节点数在范围 [0, 5000] 内
-104 <= Node.val <= 104
优秀解答:[育树霖疯]平衡二叉树(Java视频讲解,清晰易懂带字幕)
C代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int deep(struct TreeNode* node){
//退出条件
if(node==NULL) return 0;
//单层逻辑:计算深度
//深度=Max(左节点深度,右节点深度)+1
return fmax(deep(node->left),deep(node->right))+1;
}
bool isBalanced(struct TreeNode* root){
//根结点为NULL一定是
if(root==NULL) return true;
//还要排除对称二叉树的情况 这种情况看子问题时是false,但是总体看,是true
/*
1
2 3
2 5
4 6
*/
//if(!root->left||!root->right) return false;
if(!isBalanced(root->left)||!isBalanced(root->right)) return false;
int leftDeep = deep(root->left);
int rightDeep = deep(root->right);
return fabs(leftDeep-rightDeep)>1?false:true;
}
111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
提示:
树中节点数的范围在 [0, 105] 内
-1000 <= Node.val <= 1000
来源:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
没有考虑到只有一颗子树的情况,如图
return fmin(leftDeep,rightDeep)+1;
是错误的,考虑的情况欠缺。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int minDepth(struct TreeNode* root){
if(root==NULL) return 0;
if(root->left==NULL&&root->right==NULL) return 1;
int leftDeep = minDepth(root->left);
int rightDeep= minDepth(root->right);
// 如果左子树或右子树的深度有一个为 0,即只存在一个子树,那么当前子树的最小深度就是该子树的深度+1
// 如果左子树和右子树的深度都不为 0,即左右子树都存在,那么当前子树的最小深度就是它们较小值+1
return (leftDeep== 0 || rightDeep == 0) ? leftDeep + rightDeep + 1 : fmin(leftDeep, rightDeep) + 1;
//return fmin(leftDeep,rightDeep)+1;
}