判断是不是平衡树。首先写一个函数计算一棵树的高度,我用了递归。然后遍历这棵树,看每一个结点是不是都平衡。
/**
* 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:
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true;
int left = getheight(root->left) + 1;
int right = getheight(root->right) + 1;
if(abs(left - right)>1)
return false;
else
{
if(isBalanced(root->left) && isBalanced(root->right))
return true;
else
return false;
}
}
int getheight(TreeNode* root)
{
if(root == NULL)
return 0;
if(root->left == NULL && root->right == NULL)
return 1;
int left = getheight(root->left) + 1;
int right = getheight(root->right) + 1;
return left > right ? left:right;
}
};
看别人写的代码:
class Solution {
public:
int depth (TreeNode *root) {
if (root == NULL) return 0;
return max (depth(root -> left), depth (root -> right)) + 1;
}
bool isBalanced (TreeNode *root) {
if (root == NULL) return true;
int left=depth(root->left);
int right=depth(root->right);
return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
};