判断平衡二叉树是否平衡

需要一个辅助方法,计算树的高度

public int height(TreeNode root) {
        if(root == null) return 0;
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        return leftHeight>rightHeight?(leftHeight+1):(rightHeight+1);
    }


判断树是否为平衡二叉树

public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int diff = height(root.left) - height(root.right);
        if(diff<-1 || diff>1) return false;
        return isBalanced(root.left)&&isBalanced(root.right);
    }
    
}
    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/xu768840497/article/details/78535602
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞