牛客网刷题之平衡二叉树

来源:互联网 发布:阿里云os系统电脑版 编辑:程序博客网 时间:2024/06/06 05:14

题目描述:

这里写图片描述

解题思路:

  首先要知道平衡二叉树的特点:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。那么,如果数不为空的话,我们乐意分别递归求出左右子树的高度,如果大于1就返回false,否则就返回true。

题解:

boolean isBalance = true;    public boolean IsBalanced_Solution(TreeNode root) {        getDeep(root);        return isBalance;    }    public int getDeep(TreeNode root) {        if(root == null){            return 0;        }        int leftDeep = getDeep(root.left);        int rightDeep = getDeep(root.right);        if(Math.abs(leftDeep-rightDeep) > 1){            isBalance = false;        }        return Math.max(leftDeep, rightDeep) + 1;    }

ac结果:

这里写图片描述

0 0
原创粉丝点击