110. Balanced Binary Tree

https://leetcode.com/problems/balanced-binary-tree/description/

题目:判断二叉树是不是平衡树

思路:采用后续遍历的方式,求出左右子节点的返回值,如果左子树的返回值为-1,或者右子树的返回值为-1,或者左右子树的返回值之差的绝对值大于1,则返回-1 。否则返回max(左子树高度,右子树高度)+1。

class Solution {
public:
    int Balanced(TreeNode* root){

         int l = 0, r = 0;
         if(root->left!=NULL)  l = Balanced(root->left);
         if(root->right!=NULL) r = Balanced(root->right);


        if(l==-1||r==-1||abs(l-r)>1) return -1;

         l = l>r?l:r;

         return l+1;
    }
    bool isBalanced(TreeNode* root) {
         if(!root) return 1;
         return Balanced(root)!=-1;
    }
};

猜你喜欢

转载自blog.csdn.net/tangyuanzong/article/details/79993631