/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
int j = treeDepth(root);
if(j == -1) return false;
else return true;
}
int treeDepth(TreeNode* root){
if(root){
int m = treeDepth(root->left);
int n = treeDepth(root->right);
if(m == -1 || n == -1) return -1;
if(m-n<=1 && n-m<= 1){
return m>n?m+1:n+1;
}
else return -1;
}
else return 0;
}
};
利用递归计算每一个节点的子树深度,然后比较子树深度之差,如果大于1 返回-1,否则返回其深度, 返回值为-1说明该子树不是平衡二叉树
[Leetcode] Balanced Binary Tree
最新推荐文章于 2022-06-07 16:52:48 发布