题目:
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
示例 1:
image.png
输入:root = [3,9,20,null,null,15,7]
输出:true
示例 2:
image.png
输入:root = [1,2,2,3,3,null,null,4,4]
输出:false
示例 3:
输入:root = []
输出:true
提示:
树中的节点数在范围 [0, 5000] 内
-104 <= Node.val <= 104
链接:https://leetcode-cn.com/problems/balanced-binary-tree
思路:
1、采用递归的思想,计算左右子树的高度差。如果高度差小于1则代表平衡
Python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def treeDepth(self, root):
if not root:
return 0
ld = self.treeDepth(root.left)
rd = self.treeDepth(root.right)
if(ld>=0 and rd>=0 and (abs(ld-rd)<=1)):
return max(ld, rd)+1
else:
return -1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.treeDepth(root) >= 0
C++代码:
/**
* 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 {
public:
int treeDepth(TreeNode* root){
if(root == nullptr){
return 0;
}
int ld = treeDepth(root->left);
int rd = treeDepth(root->right);
if (ld>=0 && rd>=0 && abs(ld-rd)<=1){
return max(ld, rd) + 1;
}else{
return -1;
}
}
bool isBalanced(TreeNode* root) {
return treeDepth(root) >= 0;
}
};
网友评论