欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

判断二叉树树是否是平衡二叉树

程序员文章站 2022-05-16 11:24:19
...
package com.tree;

public class IsBalanceTree {

    public static boolean isBalanceTree(TreeNode root,int[] dep){
        if(root==null){
            dep[0] = 0;
            return true;
        }
        int[] leftDep = new int[1];
        int[] rightDep = new int[1];
        if(isBalanceTree(root.left,leftDep)&&isBalanceTree(root.right,rightDep)){
            int diff = leftDep[0]-rightDep[0];

            if(diff>=-1&&diff<=1){
                dep[0] = 1 + (leftDep[0] > rightDep[0] ? leftDep[0] : rightDep[0]);
                return true;
            }

        }
        return false;

    }



    private class TreeNode {
        private TreeNode left;
        private TreeNode right;
        private Integer val;
        public TreeNode(Integer val) {
            this.val = val;
        }
    }
}

相关标签: 算法&数据结构