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);
}
};
下面是以前整理的链接:平衡二叉树的判断
时间: 2024-08-03 11:25:28