110. 平衡二叉树
· 约 2 分钟阅读 · – 次阅读
leetcode
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
自顶向下递归
递归求高度,然后判断根节点和左右子节点是否都是平衡二叉树
计算高度和判断是否平衡分开,每个节点都需要计算至少2次 时间复杂度为O(n^2)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def height(root):
if not root:
return 0
if not root.left and not root.right:
return 1
return 1 + max(height(root.left), height(root.right))
if not root:
return True
return abs(height(root.left)-height(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int getHeight(TreeNode* root) {
int result = 0;
if (root == nullptr) {
result = 0;
}else if (root->left == nullptr && root->right == nullptr) {
result = 1;
}else{
int l = getHeight(root->left);
int r = getHeight(root->right);
result = 1 + max(l, r);
}
return result;
}
public:
bool isBalanced(TreeNode* root) {
if (root == nullptr) return true;
return abs(getHeight(root->left)-getHeight(root->right))<=1 && isBalanced(root->left) && isBalanced(root->right);
}
};
计算高度的时候 顺便判断是否是平衡二叉树
-1表示非平衡二叉树,否则为高度
每个节点只需要计算一次,时间复杂度为O(n)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def height(root):
if not root:
return 0
if not root.left and not root.right:
return 1
left = height(root.left)
right = height(root.right)
if left == -1 or right == -1 or abs(left-right) > 1:
return -1
else:
return 1 + max(left, right)
return height(root) >= 0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int getHeight(TreeNode* root) {
if (root == nullptr) return 0;
if (root->left == nullptr && root->right == nullptr) return 1;
int l = getHeight(root->left);
int r = getHeight(root->right);
if (l == -1 || r == -1 || abs(l - r) > 1) return -1;
return 1 + max(l, r);
}
public:
bool isBalanced(TreeNode* root) {
if (root == nullptr) return true;
return getHeight(root) >= 0;
}
};