Q:输入一棵二叉树,判断该二叉树是否是平衡二叉树。
A:
结合上一题的计算树的高度。
bool IsBalanced_Solution(TreeNode *pRoot) {
vector<int> diff = {-1, 0, 1};
if (pRoot == nullptr)
return true;
int l = TreeDepth(pRoot->left);
int r = TreeDepth(pRoot->right);
int d = l - r;
vector<int>::iterator it;
it = find(diff.begin(), diff.end(), d);
if (it == diff.end())
return false;
else {
bool left = IsBalanced_Solution(pRoot->left);
bool right = IsBalanced_Solution(pRoot->right);
return left && right;
}
}
int TreeDepth(TreeNode *pRoot) {
if (pRoot == nullptr)
return 0;
int l = TreeDepth(pRoot->left);
int r = TreeDepth(pRoot->right);
return l > r ? l + 1 : r + 1;
}
但这样做有一个问题,就是下层一直累积遍历很多次。这样直接在遍历过程中进行判断。
bool IsBalanced(TreeNode *root, int & dep){
if(root == NULL){
return true;
}
int left = 0;
int right = 0;
if(IsBalanced(root->left,left) && IsBalanced(root->right, right)){
int dif = left - right;
if(dif<-1 || dif >1)
return false;
dep = (left > right ? left : right) + 1;
return true;
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
int dep = 0;
return IsBalanced(pRoot, dep);
}