前言
LeetCode blabla Tree系列稍微不太水的一道题,很有使用价值(可以牵扯到AVL树的概念什么的)。递归仍然是不二选择。
题目
https://leetcode.com/problems/balanced-binary-tree/
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
判断一棵二叉树是不是平衡树,这里的标准是每个节点的两个子树深度都不会相差超过1。
分析
写一个辅助函数用于计算树深Depth即可,具体见代码,写的很清晰。
代码
class Solution {
public:
int Depth(TreeNode* root) {
if (root == NULL) return 0;
int LeftD = Depth(root->left);
int RightD = Depth(root->right);
return (LeftD+1) > (RightD+1) ? (LeftD+1) : (RightD+1);
}
bool isBalanced(TreeNode* root) {
if (root == NULL) return 1;
int Left = Depth(root->left);
int Right = Depth(root->right);
int diff = Left - Right;
if (diff > 1 || diff < -1) return 0;
return isBalanced(root->left) && isBalanced(root->right);
}
};