Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
這道題以前整理過,這裡就不細寫了,直接貼上代碼:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool fun(TreeNode* root,int& depth){
if(root==NULL){
depth=0;
return true;
}
int left,right;
if(fun(root->left,left)&&fun(root->right,right)){
int diff=left-right;
if(abs(diff)<=1){
depth=1+(left>right?left:right);
return true;
}
}
return false;
}
bool isBalanced(TreeNode *root) {
int depth=0;
return fun(root,depth);
}
};
下面是以前整理的鏈接:平衡二叉樹的判斷