题目链接: leetcode.
暴力,计算每个节点的左右子树的深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
执行用时:24 ms, 在所有 C++ 提交中击败了30.77%的用户
内存消耗:20.8 MB, 在所有 C++ 提交中击败了51.43%的用户
*/
class Solution {
public:
int calDeep(TreeNode* root)
{
if(root == nullptr)
return 0;
return max(calDeep(root -> left), calDeep(root -> right)) + 1;
}
bool isBalanced(TreeNode* root) {
if(root == nullptr)//空树当然是平衡二叉树
return true;
queue<TreeNode*> Q;
Q.push(root);
while(!Q.empty())
{
TreeNode* node = Q.front();
Q.pop();
int t = calDeep(node -> left) - calDeep(node -> right);
if(t < -1 || t > 1)
{
return false;
}
//不要把空节点再放到队列里啦
if(node -> left)
Q.push(node -> left);
if(node -> right)
Q.push(node -> right);
}
return true;
}
};
写的太复杂了,,
二叉树的每个节点的左右子树的高度差的绝对值不超过1,则二叉树是平衡二叉树。根据定义,一棵二叉树是平衡二叉树,当且仅当其所有子树也都是平衡二叉树。
因此可以使用递归的方式判断二叉树是不是平衡二叉树
自顶向下 O(n^2) O(n)
class Solution {
public:
int height(TreeNode* root) {
if (root == NULL) {
return 0;
} else {
return max(height(root->left), height(root->right)) + 1;
}
}
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
} else {
return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
}
};
//作者:LeetCode-Solution
//链接:https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/
//来源:力扣(LeetCode)
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
自底向上 不用重复算树的深度了
O(n) O(n)
/*
执行用时:12 ms, 在所有 C++ 提交中击败了90.46%的用户
内存消耗:20.2 MB, 在所有 C++ 提交中击败了97.17%的用户
*/
class Solution {
public:
int height(TreeNode* root) {
if(root == nullptr)
return 0;
int h_left = height(root -> left);
int h_right = height(root -> right);
if(h_left == -1 || h_right == -1)
return -1;
if(abs(h_left - h_right) > 1)
return -1;
return max(h_left, h_right) + 1;
}
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
return height(root) != -1;
}
};