110. 平衡二叉树+104. 二叉树的最大深度
与二叉树深度相关的题:
110. 平衡二叉树
解题思路: 判断是否为平衡二叉树,根据定义平衡二叉树(AVL),左右子树是AVL树,并且左右子树的高度差不超过1,那么这个是典型的后序遍历场景,先获取左右子树的高度,然后判断左右子树的高度差。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int helper(TreeNode* root) {
if (!root) return 0;
int leftH = helper(root->left);
int rightH = helper(root->right);
if (leftH == -1 || rightH == -1 || abs(leftH - rightH) > 1) return -1;
return max(leftH, rightH) + 1;
}
bool isBalanced(TreeNode* root) {
if (!root) return true;
return helper(root) != -1;
}
};
104. 二叉树的最大深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
111. 二叉树的最小深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode *root, int depth, int &res) {
if (!root) return;
if (root->left == NULL && root->right == NULL) {
res = min(res, depth);
return;
}
dfs(root->left, depth + 1, res);
dfs(root->right, depth + 1, res);
}
int minDepth(TreeNode* root) {
if (!root) return 0;
int res = INT_MAX;
dfs(root, 1, res);
return res;
}
};