Leet Code OJ 110. Balanced Binary Tree [Difficulty: Easy]
2016-03-16 14:02
288 查看
题目:
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。
分析:
这其实就是判断是否是平衡二叉树。
平衡二叉树,又称***L树。它或者是一棵空树,或者是具有下列性质的二叉树:它的左子树和右子树都是平衡二叉树,且左子树和右子树的高度之差之差的绝对值不超过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.
翻译:
给定一个二叉树,检测它是否是高度平衡的。
这个问题中,一个高度平衡的二叉树是定义在一个二叉树上,它的每个节点的两棵子树的高度相差都不超过1。
分析:
这其实就是判断是否是平衡二叉树。
平衡二叉树,又称***L树。它或者是一棵空树,或者是具有下列性质的二叉树:它的左子树和右子树都是平衡二叉树,且左子树和右子树的高度之差之差的绝对值不超过1。
下面的做法,递归遍历每个节点,每次递归,都获取左右子树的高度进行判断,采用-1作为已经检测到不平衡的标志位,其余情况返回当前子树的高度,用作上一层递归判断。
代码:
[code]/** * 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) { int depth=getDepth(root,0); return depth!=-1;//-1代表子树出现不平衡 } public int getDepth(TreeNode root,int length){ if(root==null){ return length; } int leftDepth=getDepth(root.left,length+1); int rightDepth=getDepth(root.right,length+1); if(leftDepth==-1||rightDepth==-1||leftDepth-rightDepth>1||rightDepth-leftDepth>1){ return -1; } return leftDepth>rightDepth?leftDepth:rightDepth; } }
相关文章推荐
- HashMap和ConcurrentHashMap研究
- 遮挡剔除技术分析
- 互联网TCP/IP五层模型(一)
- 4-5 链式表操作集
- C# 数组
- SYN591-B型 转速表
- 在PLSQL中编译复杂的java(转)
- 词频统计
- Activity.runOnUiThread(Runnable)简单介绍
- .sh脚本语法
- jdbc
- Android Studio Svn一般忽略哪些文件和文件夹
- maven-pom文件详解
- SYN591-A型 计数器
- python学习5 常用三方模块
- 46. Permutations
- poj2823
- Checkstyle的配置详解
- switf 字符串转 json数据 ,json数据再转化为数组
- ANDROID 面试问题归纳