Balanced Binary Tree--LeetCode
时间:2015-04-05 12:02:53
收藏:0
阅读:104
判断一个二叉树是否为平衡二叉树
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; } }
两段代码一样,只不过第一段比较简单
评论(0)