題目鏈接:click~
/*題意:判斷一顆平衡二叉樹是否平衡*/
/**
*思路:平衡二叉樹的每個結點的左右子樹的深度差不超過1
* DFS記錄每個結點的左右子樹的深度,判斷是否平衡
*/
class Solution {
public:
bool Judge(TreeNode *T, int &dep) {
if(T == NULL) {
dep = 0;
return true;
}
int leftdepth, rightdepth;
bool leftBalance = Judge(T->left, leftdepth);
bool rightBalance = Judge(T->right, rightdepth);
dep = max(leftdepth, rightdepth) + 1;
return leftBalance && rightBalance && (abs(leftdepth-rightdepth) <= 1);
}
bool isBalanced(TreeNode *root) {
int dep;
return Judge(root, dep);
}
};