判断二叉树是否是平衡二叉树

采用树形dp的方法判断,详情参见《程序员代码面试指南》P146。

package com.gxu.dawnlab_algorithm4;
/**
 * 判断二叉树是否是平衡二叉树
 * @author junbin
 *
 * 2019年6月29日
 */
public class IsBalancedTree {
	
	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int data) {
			this.value = data;
		}
	}
	
	public static class ReturnType{
		public boolean isBlance;
		public int height;
		
		public ReturnType(boolean isBlance,int height){
			this.isBlance = isBlance;
			this.height = height;
		}
	}
	
	public static ReturnType process(Node head){
		if(head == null){ //base case 空树也是平衡树
			return new ReturnType(true,0);
		}
		
		ReturnType leftType = process(head.left);
		ReturnType rightType = process(head.right);
		int height = Math.max(leftType.height, rightType.height) + 1;
		boolean isBlance = leftType.isBlance && rightType.isBlance && (Math.abs(leftType.height - rightType.height)<2);
		return new ReturnType(isBlance,height);
	}
	
	public static boolean isBalance(Node head){
		return process(head).isBlance;
	}
	
	public static void main(String[] args) {
		Node head = new Node(1);
		head.left = new Node(2);
		head.right = new Node(3);
		head.left.left = new Node(4);
		head.left.right = new Node(5);
		head.right.left = new Node(6);
		head.right.right = new Node(7);
//		head.right.left.right = new Node(8);

		System.out.println(isBalance(head));
	}
}

 

你可能感兴趣的:(面试题----二叉树问题)