解法1:
暴力遍历,时间复杂度较高。
#include <iostream>
#include<stdio.h>
using namespace std;
struct BinaryTreeNode{
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
int treeDeep(BinaryTreeNode* root){
if(root==NULL){
return 0;
}
int left,right;
left = treeDeep(root->left);
right = treeDeep(root->right);
return (left>right?left:right)+1;
}
bool isBalance(BinaryTreeNode* root){
if(root==NULL){
return true;
}
int left = treeDeep(root->left);
int right = treeDeep(root->right);
int diff = left-right;
if(diff>1||diff<-1){
return false;
}
return isBalance(root->left)&&isBalance(root->right);
}
int main()
{
return 0;
}
解法二:
#include <iostream>
#include<stdio.h>
using namespace std;
struct BinaryTreeNode{
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
bool isBalanced(BinaryTreeNode* root,int&depth){
if(root==NULL){
depth = 0;
return true;
}
int left,right;
if(isBalanced(root->left,left)&&isBalanced(root->right,right)){
int diff = left - right;
if(diff<=1&&diff>=-1){
depth = left>right?left+1:right+1;
return true;
}
}
return false;
}
bool isBalanced(BinaryTreeNode* root){
int depth = 0;
return isBalanced(root,depth);
}
int main()
{
return 0;
}