判断是否为平衡树易错点

整体思路

        采用递归的方法,一层一层求节点的左子树和右子树的高度以及左子树和右子树是否平衡

易错点

        本题的思路很简单,更加具体的思路csdn上其他博客应该已经写得很详细了。本篇主要讲讲本题的易错点。以某个节点为头的树的高度 = 左子树和右子树的高度的最大值 + 1。注意!!!+1真的很容易忽略

代码

public static boolean isBalanced3(Node head) {
		if(head == null){
			return true;
		}
		return process2(head).isBalanced;
	}
	public static Info2 process2(Node head){
		if(head == null){
			return new Info2(true,0);
		}
		Info2 leftInfo = process2(head.left);
		Info2 rightInfo =process2(head.right);
		boolean isBalanced = true;
		if(!leftInfo.isBalanced){
			isBalanced = false;
		}
		if(!rightInfo.isBalanced){
			isBalanced = false;
		}
		if(Math.abs(leftInfo.height - rightInfo.height) >1){
			isBalanced = false;
		}
		int height = Math.max(leftInfo.height,rightInfo.height) + 1;
		return new Info2(isBalanced,height);
	}
	public static class Info2{
		public boolean isBalanced;
		public int height;
		public Info2(boolean isBalanced,int height){
			this.isBalanced = isBalanced;
			this.height = height;
		}
	}

你可能感兴趣的:(算法,一些小坑,算法,数据结构)