您的位置:首页 > Web前端

《剑指offer》-判断二叉树是否是平衡二叉树

2018-01-31 09:34 459 查看
/*
* 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
* 平衡二叉树的定义:是一个空树或者是一种二叉排序树,其中每一个节点的左子树和右子树的高度差至多等于 1
* 平衡二叉树一定是二叉排序树,但是二叉排序树不一定是平衡二叉树
*/
public class IsBalanced_Solution {
//法一:求某个节点的深度:前序遍历,从上往下,造成了底层节点的重复遍历
public boolean isBalanced_Solution(TreeNode root) {
if(root == null)	return true;

//求其左右节点的深度
int	leftDepth = TreeDepth(root.left);
int rightDepth = TreeDepth(root.right);
int depth_diff = leftDepth - rightDepth;

if(depth_diff < -1 || depth_diff > 1)	return false;

return isBalanced_Solution(root.left) && isBalanced_Solution(root.right);

}

//法二:求某个节点的深度:后序遍历,从下往上,避免了底层节点的重复遍历
boolean isBalanced = true;
public int TreeDepth(TreeNode root) {
if(root == null) {
return 0;
}

int	nLeft = TreeDepth(root.left);
int nRight = TreeDepth(root.right);

if(Math.abs(nLeft - nRight) > 1) {
isBalanced = false;
}

return nLeft > nRight ? (nLeft + 1) : (nRight + 1);

}

public boolean isBalanced_Solution2(TreeNode root) {
if(root == null)	return true;
TreeDepth(root);
return isBalanced;
}

public static void main(String[] args) {
TreeNode root1 = new TreeNode(5);
root1.left = new TreeNode(4);
root1.right = new TreeNode(6);

root1.left.left = new TreeNode(3);
root1.left.right = new TreeNode(2);

root1.left.left.left = new TreeNode(2);
root1.left.left.right = new TreeNode(1);

root1.left.left.left.left = new TreeNode(1);

System.out.println(new IsBalanced_Solution().isBalanced_Solution2(root1));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息