剑指offer-39-平衡二叉树
平衡二叉树
http://www.nowcoder.com/questionTerminal/8b3b95850edb4115918ecebdf1b4d222
思路
平衡二叉树的定义,空树或者两颗子树的高度差小于等于1,注意一定是子树的高度差。
代码
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null){return true;}
int h1=TreeDepth(root.left);//一定是子树的高度差
int h2=TreeDepth(root.right);
if(Math.abs(h1-h2)>1){
return false;
}
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
public int TreeDepth(TreeNode root) {
if(root==null){return 0;}
return 1+Math.max(TreeDepth(root.left),TreeDepth(root.right));
}
} 剑指offer与数据结构 文章被收录于专栏
本专栏包括剑指offer题目和一些刷题用的数据结构,单调栈,树状数组,差分数组,后面还会更新红黑树等较为复杂的数据结构
