剑指Offer39:平衡二叉树(Java)

左程云算法视频:https://pan.baidu.com/s/13eMIXzcbc3BXtLGe76hV8g 提取码:onci

思路分析:

二叉树的题第一反应是应用递归遍历。
判断一棵平衡二叉树的依据是:1.结点的左右子树的深度是平衡二叉树,2.左子树的深度与右子树的深度的差不超过1 若所有的结点都符合这两条件则该树是一平衡二叉树。

利用“与”实现遇到错返回false,全部正确才返回true(之前一直不懂,终于清楚了)

boolean m=true;
        if(a-b>1||a-b<-1){
            m=false;
        }
        boolean l=IsBalanced_Solution (root.left);
        boolean r=IsBalanced_Solution (root.right);
        return l&&r&&m;

题目描述:

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

Java代码一(参考左程云进阶视频5):

import java.lang.Math;
public class Solution {
    public static class Returndata{
        public boolean judge;
        public int deepth;
        public Returndata(boolean judge,int deepth){
            this.judge=judge;
            this.deepth=deepth;
        }
    }
    public boolean IsBalanced_Solution(TreeNode root) {
        return IsBalanceTree(root).judge;
    }
    public static Returndata IsBalanceTree(TreeNode root){
        if(root==null){
            return new Returndata(true,0);
        }
        if(!IsBalanceTree(root.left).judge){
            return new Returndata(false,0);
        }
        if(!IsBalanceTree(root.right).judge){
            return new Returndata(false,0);
        }
        int a=IsBalanceTree(root.left).deepth;
        int b=IsBalanceTree(root.right).deepth;
        if(a-b>1||a-b<-1){
            return new Returndata(false,0);
        }
        else {
            return new Returndata(true,Math.max(a,b)+1);
        }
    }
} 

Java代码二:

//遇到错返回false,全部正确才返回true;
//二叉树的题第一反应是应用递归遍历。
import java.lang.Math;
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null){
            return true;
        }
        int a=deepth(root.left);
        int b=deepth(root.right);
        boolean m=true;
        if(a-b>1||a-b<-1){
            m=false;
        }
        boolean l=IsBalanced_Solution (root.left);
        boolean r=IsBalanced_Solution (root.right);
        return l&&r&&m; //若其中一项结果是false最终结果就会是false 全部是true才会返回true.
    }
    public int deepth(TreeNode cur){  //求某一结点的深度(就是剑指Offer第38题)
        if(cur==null){
            return 0;
        }
        int a=deepth(cur.left);
        int b=deepth(cur.right);
        return Math.max(a,b)+1;
    }  
} 
原文地址:https://www.cnblogs.com/dongmm031/p/12244923.html