Balanced Binary Tree
2015-06-06 15:53
387 查看
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
思路:对于每一个结点先求出左子树的高度和右子树的高度,然后判断它们的高度差,如果高度相差大于1则不是平衡二叉树,如果小于1,继续判断它的左子树和右子树是不是平衡二叉树。
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
思路:对于每一个结点先求出左子树的高度和右子树的高度,然后判断它们的高度差,如果高度相差大于1则不是平衡二叉树,如果小于1,继续判断它的左子树和右子树是不是平衡二叉树。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { if(root==null) return true; int left=sub_height(root.left); int right=sub_height(root.right); int diff=Math.abs(left-right); if(diff>1) return false; else return isBalanced(root.left) && isBalanced(root.right); } public int sub_height(TreeNode subTree) { if(subTree==null) return 0; if(subTree.left==null && subTree.right==null) return 1; if(subTree.left==null) return sub_height(subTree.right)+1; if(subTree.right==null) return sub_height(subTree.left)+1; return Math.max(sub_height(subTree.right),sub_height(subTree.left))+1; } }
相关文章推荐
- 13.1.6
- iOS UILabel自动换行,自适应高度
- HBase Coprocessor to Index Columns into ElasticSearch
- 1第一个Android应用程序
- oracle 的select初步
- Redis安装搭建
- 微信js sdk invalid signature签名错误 问题解决。
- was install 下载地址
- Effective C++ 条款44
- lintcode 1: Data Stream Median
- 编程技术面试的五大要点
- 五子棋AI算法浅谈
- Hibernate学习-Hibernate查询语言HQL
- Fault管理与自动化
- flash中声音的控制
- 委托和接口
- 读取、写入properties文件
- 简单的内存对齐
- 包含min函数的栈
- python 装饰器 decorator