- 01.题目要求
- 02.问题分析
- 03.实例代码
- 博客笔记大汇总【15年10月到至今】,包括Java基础及深入知识点,Android技术博客,Python学习笔记等等,还包括平时开发中遇到的bug汇总,当然也在工作之余收集了大量的面试题,长期更新维护并且修正,持续完善……开源的文件是markdown格式的!同时也开源了生活博客,从12年起,积累共计N篇[近100万字,陆续搬到网上],转载请注明出处,谢谢!所有博客陆续更新到GitHub上!
- 链接地址:https://github.com/yangchong211/YCBlogs
- 如果觉得好,可以star一下,谢谢!当然也欢迎提出建议,万事起于忽微,量变引起质变!
- 问题如下所示:
- 输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1 ,那么它就是一棵平衡二叉树。
- 示例 :
解法一:需要重蟹遍历结点多次的解法 在遍历树的每个结点的时候,调用函数treeDepth得到它的左右子树的深度。如果每个结点的左右子树的深度相差都不超过1 ,按照定义它就是一棵平衡的二叉树。
解法二:每个结点只遍历一次的解法 用后序遍历的方式遍历二叉树的每一个结点,在遍历到一个结点之前我们就已经遍历了它的左右子树。只要在遍历每个结点的时候记录它的深度(某一结点的深度等于它到叶节点的路径的长度),我们就可以一边遍历一边判断每个结点是不是平衡的。
- 如下所示
public class Test { private static class BinaryTreeNode { int val; BinaryTreeNode left; BinaryTreeNode right; public BinaryTreeNode() { } public BinaryTreeNode(int val) { this.val = val; } } public static int treeDepth(BinaryTreeNode root) { if (root == null) { return 0; } int left = treeDepth(root.left); int right = treeDepth(root.right); return left > right ? (left + 1) : (right + 1); } /** * 判断是否是平衡二叉树,第一种解法 * * @param root * @return */ public static boolean isBalanced(BinaryTreeNode root) { if (root == null) { return true; } int left = treeDepth(root.left); int right = treeDepth(root.right); int diff = left - right; if (diff > 1 || diff < -1) { return false; } return isBalanced(root.left) && isBalanced(root.right); } /** * 判断是否是平衡二叉树,第二种解法 * * @param root * @return */ public static boolean isBalanced2(BinaryTreeNode root) { int[] depth = new int[1]; return isBalancedHelper(root, depth); } public static boolean isBalancedHelper(BinaryTreeNode root, int[] depth) { if (root == null) { depth[0] = 0; return true; } int[] left = new int[1]; int[] right = new int[1]; if (isBalancedHelper(root.left, left) && isBalancedHelper(root.right, right)) { int diff = left[0] - right[0]; if (diff >= -1 && diff <= 1) { depth[0] = 1 + (left[0] > right[0] ? left[0] : right[0]); return true; } } return false; } }
- 我的个人站点:
- github:https://github.com/yangchong211
- 知乎:https://www.zhihu.com/people/yczbj/activities
- 简书:http://www.jianshu.com/u/b7b2c6ed9284
- csdn:http://my.csdn.net/m0_37700275
- 喜马拉雅听书:http://www.ximalaya.com/zhubo/71989305/
- 开源中国:https://my.oschina.net/zbj1618/blog
- 泡在网上的日子:http://www.jcodecraeer.com/member/content_list.php?channelid=1
- 邮箱:yangchong211@163.com
- 阿里云博客:https://yq.aliyun.com/users/article?spm=5176.100- 239.headeruserinfo.3.dT4bcV
- segmentfault头条:https://segmentfault.com/u/xiangjianyu/articles
- 掘金:https://juejin.im/user/5939433efe88c2006afa0c6e