【easy】110. Balanced Binary Tree判断二叉树是否平衡
判断二叉树是否平衡
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.
以下解法为什么时间复杂度为O(n)?
/** * 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: int cntHeight(TreeNode *root) { if(root == NULL) return 0; int l = cntHeight(root->left); int r = cntHeight(root->right); if(l < 0 || r < 0 || abs(l-r) > 1) return -1; //自定义 return -1,表示不平衡的情况 else return max(l, r) + 1; //******* } bool isBalanced(TreeNode *root) { if(root == NULL) return true; int l = cntHeight(root->left); //-1表示不平衡 int r = cntHeight(root->right); //-1表示不平衡 if(l < 0 || r < 0 || abs(l-r) > 1) return false; else return true; } };