/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
int a = NodeHeight(root);
return isOk(root);
}
int NodeHeight(TreeNode *root)
{
if(root == NULL)
return 0;
root->val = 0;
if(root->left == NULL && root->right == NULL)
return 0;
else if(root->left != NULL && root->right == NULL)
return root->val = 1 + NodeHeight(root->left);
else if(root->left == NULL && root->right != NULL)
return root->val = 1 + NodeHeight(root->right);
else
return root->val = 1 + max(NodeHeight(root->left), NodeHeight(root->right));
}
bool isOk(TreeNode *root)
{
if(root == NULL)
return true;
TreeNode *leftNode = root->left;
TreeNode *rightNode = root->right;
if(leftNode == NULL && rightNode == NULL)
return true;
else if(leftNode != NULL && rightNode == NULL)
{
if(leftNode->val >= 1)
return false;
else
return true;
}
else if(leftNode == NULL && rightNode != NULL)
{
if(rightNode->val >= 1)
return false;
else
return true;
}
else
{
if(abs(leftNode->val - rightNode->val) >= 2)
return false;
else
return (isOk(leftNode) && isOk(rightNode));
}
}
};
思路是,第一次遍历,通过NodeHeight()函数设置各节点的高度,第二次遍历,通过对比各节点的高度,判断
是否是平衡二叉树。由于两次递归遍历树,因此效率不高,而且代码写得也比较臃肿。
贴出网友的代码,思路一样,但是代码简捷多了
class Solution {
int maxDepth(TreeNode *root){
if(NULL == root){
return 0;
}
int maxL = maxDepth(root->left);
int maxR = maxDepth(root->right);
return 1 + (maxL > maxR ? maxL : maxR);
}
public:
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(NULL == root){
return true;
}
int diff = maxDepth(root->left) - maxDepth(root->right);
if((diff>1) || (diff<-1)){
return false;
}
return isBalanced(root->left) && isBalanced(root->right);
}
};