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

/*
 * 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
 * 平衡二叉树的定义:是一个空树或者是一种二叉排序树,其中每一个节点的左子树和右子树的高度差至多等于 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));
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值