给定一个二叉树,判断它是否是 平衡二叉树
平衡二叉树:二叉树的每个节点的左右子树的高度差的绝对值不超过 1,则二叉树是平衡二叉树,一棵二叉树是平衡二叉树,当且仅当其所有子树也都是平衡二叉树
根据平衡二叉树特有的性质,可以用递归方法判断自顶向下或者自底向上递归
C语言写法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxheight(struct TreeNode *p)
{
if(p==NULL)return 0;
return fmax(maxheight(p->left),maxheight(p->right))+1;
}
bool isBalanced(struct TreeNode* root) {
if(root==NULL)return true;
return fabs(maxheight(root->left)-maxheight(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right);
}
python写法
# 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: TreeNode) -> int:
if not root:
return 0
return max(height(root.left), height(root.right)) + 1
if not root:
return True
return abs(height(root.left) - height(root.right)) <= 1
Java写法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null)return true;
else return Math.abs(height(root.left)-height(root.right))<=1&&isBalanced(root.left)&&isBalanced(root.right);
}
public int height(TreeNode root)
{
if (root==null)
return 0;
else{
return Math.max(height(root.left),height(root.right))+1;
}
}
}