平衡二叉树

给定一个二叉树,判断它是否是 平衡二叉树

 平衡二叉树:二叉树的每个节点的左右子树的高度差的绝对值不超过 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;
        }
    }
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值