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.
判断是否是平衡树,很想用非递归做,发现自己没有那个能力,最后乖乖写递归。
按道理来说,由下而上的递归,复杂度绝对是更低的O(n)。不过由上而下的也贴一下吧O(n^2)。
/**
* 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 { //由上而下递归O(n^2)
public:
bool isBalanced(TreeNode* root) {
if (!root) return true;
int le = depth(root->left);
int ri = depth(root->right);
return abs(le-ri) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
int depth(TreeNode* root) {
if (!root) return 0;
return max(depth(root->left), depth(root->right)) + 1;
}
};
/**
* 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 { //由下而上递归O(n)
public:
bool isBalanced(TreeNode* root) {
return depth(root) != -1;
}
int depth(TreeNode* root) {
if (!root) return 0;
int le = depth(root->left);
if (le == -1) return -1;
int ri = depth(root->right);
if (ri == -1) return -1;
if (abs(le - ri) > 1) return -1;
return 1 + max(le, ri);
}
};