zoukankan      html  css  js  c++  java
  • 二叉树——判断一棵树是否是平衡二叉树

    平衡二叉树 (空树或者左右两个孩子高度差不超过1)

    在涉及到二叉树的题目时,递归函数非常好用

    列出可能性-》整理出返回值的类型-》整个递归过程按照同样的结构得到子树的信息,整合子树的信息,加工出应该返回的信息,向上返回

    1.左子树是否平衡

    2.右子树是否平衡

    3.左子树的高度

    4.右子树的高度

    根据可能性,使用递归函数

    可能性-》返回值的类型  

    //列出可能性  左右子树是否分别平衡,若平衡后,左右子树的高度
        public static class ReturnData{
            boolean isB;
            int high;
    
            public ReturnData(boolean isB, int high){
                this.isB = isB;
                this.high = high;
            }
        }
    

      

    整个递归过程按照同样的结构得到子树的信息(左子树和右子树分别是否平衡,以及它们的高度),整合子树的信息(左右子树的高度差是否符合要求),加工出返回的信息(应该返回左右子树中,高度较大的那一个high+1

    public static ReturnData process(Tree tree){
            if(tree == null) return new ReturnData(true, 0);
    
    
            ReturnData leftData = process(tree.left);
            if(!leftData.isB){
                return new ReturnData(false, 0);
            }
    
            ReturnData rightData = process(tree.right);
            if(!rightData.isB){
                return new ReturnData(false, 0);
            }
    
            if(Math.abs(leftData.high - rightData.high) > 1){
                return new ReturnData(false, 0);
            }
    
            return new ReturnData(true, Math.max(leftData.high, rightData.high) + 1);
        }
    

      

    整体的代码

    public class IsBanlancedTree {
    
        //列出可能性  左右子树是否分别平衡,若平衡后,左右子树的高度
        public static class ReturnData{
            boolean isB;
            int high;
    
            public ReturnData(boolean isB, int high){
                this.isB = isB;
                this.high = high;
            }
        }
    
    
        public static ReturnData process(Tree tree){
            if(tree == null) return new ReturnData(true, 0);
    
    
            ReturnData leftData = process(tree.left);
            if(!leftData.isB){
                return new ReturnData(false, 0);
            }
    
            ReturnData rightData = process(tree.right);
            if(!rightData.isB){
                return new ReturnData(false, 0);
            }
    
            if(Math.abs(leftData.high - rightData.high) > 1){
                return new ReturnData(false, 0);
            }
    
            return new ReturnData(true, Math.max(leftData.high, rightData.high) + 1);
        }
    
        public static boolean isBanlancedTree(Tree tree){
            return process(tree).isB;
        }
    }
    

      

      

  • 相关阅读:
    vue笔记
    vue工具
    vue笔记
    vuex
    css方法
    html2canvas
    Fiddler
    vue经验
    vue经验
    html2canvas
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8947290.html
Copyright © 2011-2022 走看看