判断一个二叉树是否为平衡二叉树
int Depth(BinTree* root) { if(root == NULL) return 0; return max(Depth(root->left),Depth(root->right))+1; } bool isBalancedBinTree(BinTree* root) { if(root ==NULL) return 1; int leftdepth = Depth(root->left); int rightdepth=Depth(root->right); if( abs(leftdepth-rightdepth)<=1) return isBalancedBinTree(root->left)&&isBalancedBinTree(root->right); else return 0; }
int height(BinTree *root) { if(root == NULL) { return 0; } else { if(root->left == NULL) { return height(root->right) + 1; } else if(root->right == NULL) { return height(root->left) + 1; } else { int l = height(root->left); int r = height(root->right); return l<r?(r+1):(l+1); } } } bool isBalanced(BinTree *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL) { return true; } else { int l = height(root->left); int r = height(root->right); if(l-r >= -1 && l-r <= 1) { return isBalanced(root->left) && isBalanced(root->right); } else return false; } }
Balanced Binary Tree--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44886233