剑指offer---39.平衡二叉树

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44406146/article/details/102700526

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

解法一:递归

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null) return true;
        int left = height(root.left);
        int right = height(root.right);
        return Math.abs(left-right) <= 1&&
               IsBalanced_Solution(root.left)&&
               IsBalanced_Solution(root.right);
    }
    public int height(TreeNode root){
        if(root == null) return 0;
        int left = height(root.left)+1;
        int right = height(root.right)+1;
        return left>right?left:right;
    }
}

解法二:递归二

public class Solution {
    private boolean flag = true;  //在求树高过程中把结果保存
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null) return true;
        height(root);
        return flag;
    }
    private int height(TreeNode root){
        if(root==null) return 0;
        int left = height(root.left);
        int right = height(root.right);
        if(Math.abs(left-right)>1){
            flag = false;  //但是并没有停止还是会继续遍历下边的节点
        }
        return Math.max(left,right)+1;
    }
}

解法三:递归三

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return height(root) != -1; //等于-1说明不平衡
    }
    //不平衡直接返回退出不必遍历所有节点
    private int height(TreeNode root){
        if(root==null) return 0;
        int left = height(root.left);
        if(left==-1) return -1;
        int right = height(root.right);
        if(right==-1) return -1;
        return Math.abs(left-right)>1?-1:(1+Math.max(left,right));
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44406146/article/details/102700526