LeetCode110-Balanced Binary Tree
2015-08-27 21:15
435 查看
LeetCode 110 : Balanced Binary Tree
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.
问题来源: https://leetcode.com/problems/balanced-binary-tree/
问题的大概意思是给一个二叉树,判断该树是否为平衡二叉树(平衡二叉树的判断条件:左右子树的高度相差最大不超过1)。
解题思路:通过递归找出每一个二叉树的左右子树的高度,然后比较左右子树高度差是否不超过1。注意若该树为空也满足条件。
源代码:
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.
问题来源: https://leetcode.com/problems/balanced-binary-tree/
问题的大概意思是给一个二叉树,判断该树是否为平衡二叉树(平衡二叉树的判断条件:左右子树的高度相差最大不超过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(null==root){ return true; } else{ return isBalancedTree(root); } } private boolean isBalancedTree(TreeNode node){ if(null==node){ return true; } else{ int leftChildHeight = getHeight(node.left); int rightChildHeight = getHeight(node.right); return (Math.abs(leftChildHeight-rightChildHeight)<=1) && isBalancedTree(node.left) && isBalancedTree(node.right); } } private int getHeight(TreeNode node){ if(null==node){ return 0; } else{ int leftChildHeight = getHeight(node.left); int rightChildHeight = getHeight(node.right); return (leftChildHeight >= rightChildHeight) ? leftChildHeight+1 : rightChildHeight+1; } } }
相关文章推荐
- 21道工作中总结的iOS高频面试题
- Linux磁盘管理
- HtmlHelper与扩展方法
- 两张图说明双向链表
- 之前设计的学校的大物实验网上预习系统
- Junit(3)JUnit和单元测试入门简介
- swift详解之十三 -----------AppDelegate
- 编程之美-字符串移位包含的问题
- iOS-点餐系统
- STL中stack/queue/map以及Boost unordered_map 的使用方法
- HDU 2609
- HDU 2609
- [leetcode-200]Number of Islands(java)
- Java数据结构-线性表之栈的应用-递归及其应用
- JUnit(4)单元测试利器 JUnit 4
- 基于七牛Python SDK写的一个批量下载脚本
- win7主机与linux虚拟机共享方法之右键添加Sharing Options
- 设置静态ip
- Cookie 和 Session 的区别
- 二、MDT 2013 Update 1平台安装