标签:boolean treenode else his amp 二叉树 this val als
public class 平衡二叉树
{
public class TreeNode
{
TreeNode left;
TreeNode right;
int val;
TreeNode(int x)
{
this.val = x;
}
}
// 获取深度
private int getDepth(TreeNode tree, int currentDepth)
{
if (tree == null)
{
return currentDepth;
}
return Math.max(getDepth(tree.left, currentDepth + 1),
getDepth(tree.right, currentDepth + 1));
}
// 采用递归解决
public boolean isBalanced(TreeNode root)
{
if (root == null)
{
return true;
}
int depthOfLeft = getDepth(root.left, 1);
int depthOfRight = getDepth(root.right, 1);
if (Math.abs(depthOfLeft - depthOfRight) > 1)
{
return false;
}
else
{
return isBalanced(root.left) && isBalanced(root.right);
}
}
}
标签:boolean treenode else his amp 二叉树 this val als
原文地址:http://www.cnblogs.com/qingtianBKY/p/6915417.html