struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
//check if it is a balanced tree
//so we check the diff between the max height of each branch
//all compare can be done along the way down to calculate max height
public:
int CheckHeight(TreeNode* root, bool& ans)
{
if(!root || !ans)//if is is not a balance tree already, we just return
return 0;
int leftHeight = CheckHeight(root->left, ans);
int rightHeight = CheckHeight(root->right, ans);
if(abs(leftHeight-rightHeight) > 1)
ans = false;
return max(leftHeight, rightHeight)+1;
}
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//get the height of each subtree
bool ans = true;
CheckHeight(root, ans);
return ans;
}
};
second time
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int isBalancedUtil(TreeNode* root, bool& isValid)
{
if(root == NULL) return 0;
if(!isValid) return -1;
int leftHeight = isBalancedUtil(root->left, isValid);
int rightHeight = isBalancedUtil(root->right, isValid);
if(abs(leftHeight-rightHeight) > 1) isValid = false;
return max(leftHeight, rightHeight)+1;
}
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool ans = true;
isBalancedUtil(root, ans);
return ans;
}
};
本文介绍了一种用于判断二叉树是否为平衡二叉树的算法实现。通过递归方式计算二叉树各子树的高度差,若任意两棵子树的高度差不超过1,则认为该二叉树为平衡二叉树。文章提供了完整的C++代码示例。

被折叠的 条评论
为什么被折叠?



