java语言判断一棵树是否是平衡二叉树(递归和迭代)

本文介绍了如何使用Java语言判断一棵树是否为平衡二叉树,分别提供了递归和迭代两种解决方案。递归方法通过比较左右子树的高度差来判断,迭代方法则利用队列进行层次遍历来实现。详细代码实现和解析帮助理解这一数据结构问题。
摘要由CSDN通过智能技术生成

目录

1.题目描述

2.递归实现

3.迭代实现


1.题目描述

2.递归实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return (Math.abs(left-right)<2)&&isBalanced(root.left)&&isBalanced(root.right);
    }
    public static int maxDepth(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return (left>right?left:right)+1;
    }
}

3.迭代实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class IsBalance{
    public int height;
    public boolean balance;
}
class Solution {
    public static IsBalance function(TreeNode root){
        IsBalance res = new IsBalance();
        res.height = 0;
        res.balance = true;
        if(root == null){
            return res;
        }
        IsBalance lres = new IsBalance();
        lres = function(root.left);
        if(lres.balance==false){
            return lres;
        }
        IsBalance rres = new IsBalance();
        rres = function(root.right);
        if(rres.balance==false){
            return rres;
        }
        res.height = (lres.height>rres.height)?lres.height+1:rres.height+1;
        res.balance = Math.abs(lres.height-rres.height)<2;
        return res;
    }
    public boolean isBalanced(TreeNode root) {
        return function(root).balance;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值