剑指Offer 39题 二叉树的深度 && 判断平衡二叉树 Java版

package test;


public class TreeDepth {
	
	public class BinaryTreeNode{
		int  m_nValue;
		BinaryTreeNode m_pLeft;
		BinaryTreeNode m_pRight;
		
	}
	
	public int treeDepth(BinaryTreeNode root){
		if(root == null){
			return 0;
		}
		
		int Left = treeDepth(root.m_pLeft);
		int Right = treeDepth(root.m_pRight);
		
		return (Left>Right)? (Left+1) :(Right+1);
		
	}
	
	public  boolean IsBalance(BinaryTreeNode root){
		if(root == null){
			return true;
		}
		
		int left = treeDepth(root.m_pLeft);
		int right = treeDepth(root.m_pRight);
		int diff = left - right;
		if(diff>1 || diff<-1){
			return false;
		}
		return IsBalance(root.m_pLeft)&& IsBalance(root.m_pRight);
		
	}
	
	public BinaryTreeNode createTree(){
		BinaryTreeNode root = new BinaryTreeNode();
		root.m_nValue = 1;
		BinaryTreeNode n2 = new BinaryTreeNode();
		n2.m_nValue = 2;
		BinaryTreeNode n3 = new BinaryTreeNode();
		n3.m_nValue = 3;
		BinaryTreeNode n4 = new BinaryTreeNode();
		n4.m_nValue = 4;
		BinaryTreeNode n5 = new BinaryTreeNode();
		n5.m_nValue = 5;
		BinaryTreeNode n6 = new BinaryTreeNode();
		n6.m_nValue = 6;
		BinaryTreeNode n7 = new BinaryTreeNode();
		n7.m_nValue = 7;
		
		root.m_pLeft = n2;
		root.m_pRight = n3;
		
		n2.m_pLeft = n4;
		n2.m_pRight = n5;
		
		n5.m_pLeft = n7;
		
		n3.m_pRight= n6;
		return root;
	}
	
	public boolean IsBalanced(BinaryTreeNode root, int pDepth){
		if(root == null){
			pDepth = 0;
			return true;
		}
		
		int left=0 ,right=0;
		
		if(IsBalanced(root.m_pLeft, left)&&IsBalanced(root.m_pRight, right)){
			int diff = left - right;
			if(diff <=1 && diff >=-1){
				pDepth = 1+(left > right? left: right);
				System.out.println("pDepth :"+pDepth+"+++++++++==root:"+root.m_nValue);
				return true;
			}
		}
		return false;
		
	}

	public boolean IsBalanced(BinaryTreeNode root){
		int pDepht = 0;
		return IsBalanced(root,pDepht);
	}
	public static void main(String[] args){
		TreeDepth treeDepth = new TreeDepth();
		
		BinaryTreeNode root = treeDepth.createTree();
		
//		System.out.println(treeDepth.treeDepth(root));
//		
//		System.out.println(treeDepth.IsBalance(root));
		System.out.println(treeDepth.IsBalanced(root));
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值