剑指offer第二版——面试题55(java)

面试题:二叉树的深度

题目一:输入一颗二叉树的根节点,求该树的深度

题目二:输入一颗二叉树的根节点,判断该树是不是平衡二叉树

方法:

题目一:

不从找路径的角度来理解树的深度。

如果一棵树只有一个节点,则它的深度为1;

如果一棵树只有左/右节点,则它的深度为左/右节点树深度+1;

如果有左节点和右节点,则它的深度为左右结点深度的较大值+1

题目二:

很自然想到,每遍历一个节点,使用题目一中的算法计算该结点的两边子结点的深度,但是缺点是会对有些节点重复进行计算,因此时间效率不高。

如果我们用后序遍历的方式遍历二叉树的每个节点,那么在遍历到一个节点之前,我们已经遍历了它的左右子树。

在遍历每个结点的时候记录它的深度,就可以一边遍历一边判断每个结点是不是平衡的

题目二代码中,如果输出-1则为不平衡,如果输出的数≥0,则为该树为平衡树,且最大深度为该数

 

代码:

public class Q55_1 {
	public static void main(String[] args) {
		BinaryTreeNode root = getTree();
		int depth = getDepth(root);
		System.out.print(depth);
	}
	
	public static int getDepth(BinaryTreeNode root) {
		if(root==null) {
			return 0;
		}
                if(root.left==null && root.right==null) {
			return 1;
		}
		
		int left = -1;
		int right = -1;
		if(root.left!=null) {
			left = getDepth(root.left);
		}
		
		if(root.right!=null) {
			right = getDepth(root.right);
		}
		
		if(right>left) {
			return right+1;
		}else {
			return left+1;
		}
	}

	// 树构造
	public static BinaryTreeNode getTree() {
		BinaryTreeNode node1 = new BinaryTreeNode(1);
		BinaryTreeNode node2 = new BinaryTreeNode(2);
		BinaryTreeNode node3 = new BinaryTreeNode(3);
		BinaryTreeNode node4 = new BinaryTreeNode(4);
		BinaryTreeNode node5 = new BinaryTreeNode(5);
		BinaryTreeNode node6 = new BinaryTreeNode(6);
		BinaryTreeNode node7 = new BinaryTreeNode(7);
		
		node1.left = node2;
		node1.right = node3;
		node2.left = node4;
		node2.right = node5;
		node5.left = node7;
		node3.right = node6;
		
		return node1;
	}
}
// 2019-06-14
	public static int isBalance(BinaryTreeNode root,int n) {
		if(root==null) {
			return n;
		}
		
		if(root.left==null && root.right==null) {
			return n+1;
		}
		
		int left = isBalance(root.left, n+1);
		int right = isBalance(root.right, n+1);
		
		if(Math.abs(left-right)<=1) {
			return max(left, right);
		}else {
			return -1;
		}
	}
	
	public static int max(int a,int b) {
		if(a>b)
			return a;
		return b;
	}



// 2019-06-04
public class Q55_2 {
	public static void main(String[] args) {
		BinaryTreeNode root = getTree();
		System.out.println(tellBalance(root,0));
	}
	
	public static int tellBalance(BinaryTreeNode root,int depth) {
		if(root==null) {
			return 0;
		}
		
		depth++;
		if(root.left==null && root.right==null) {
			return depth;
		}
		
		int left = depth;
		int right = depth;
		if(root.left!=null) {
			left = tellBalance(root.left,depth);
		}
		
		if(root.right!=null) {
			right = tellBalance(root.right,depth);
		}
		
		if(left-right>1||right-left>1) {
			return -1;
		}
		
		if(right>left) {
			return right;
		}else {
			return left;
		}
	}
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值