leetcode104. 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数
// DFS
class Solution {
public:
int maxDepth(TreeNode* root) {
// 递归出口
if(!root) return 0;
return 1+max(maxDepth(root->left), maxDepth(root->right));
}
};
110. 平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1
bool isBalanced(TreeNode* root) {
if(root == NULL) return true;
// int height = abs(dfs(root->left) - dfs(root->right));
// if(height > 1) return false;
// return true;
// 之前我忽略了,本级子数满足平衡二叉树的条件,下一层子数的子子树也要满足平衡二叉树的条件
return abs(dfs(root->left) - dfs(root->right)) <=1 && isBalanced(root->left) && isBalanced(root->right);
}
int dfs(TreeNode* root)
{
if(root == NULL) return 0;
return 1+max(dfs(root->left), dfs(root->right));
}
- 与104题求二叉树的高度是一致的