1.判断是否是平衡二叉树
定义:每个结点的左子树和右子树的高度差至多等于1 关键词条:树形DP 在树上做动态规划 思路:捋清楚问题出现的情况,然后利用递归大方向解题,设置递归条件与出口,由于需要高度以及返回值类型,所以我们需要自己封装一个返回值类型。 这种问题都是套路题 需要对递归函数有较深的理解。
(1)看左树是否是平衡二叉树 (2)再看右树是否是平衡二叉树 (3)然后是整体的高度差 看是否整体是一个平衡二叉树
public class IsBalancedTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node ( int value) {
this . value = value;
}
}
public static class ReturnData {
public int h;
public boolean isB;
public ReturnData ( boolean isB, int h) {
this . h = h;
this . isB = isB;
}
}
public static boolean isB ( Node head) {
if ( head == null) {
return true ;
}
return process ( head) . isB;
}
public static ReturnData process ( Node head) {
if ( head == null) {
return new ReturnData ( true , 0 ) ;
}
ReturnData leftData = process ( head. left) ;
if ( ! leftData. isB) {
return new ReturnData ( false , 0 ) ;
}
ReturnData rightData = process ( head. right) ;
if ( ! rightData. isB) {
return new ReturnData ( false , 0 ) ;
}
if ( Math. abs ( right. h - left. h) > 1 ) {
return new ReturnData ( false , 0 ) ;
}
return new ReturnData ( true , Math. max ( leftData. h, rightData. h) + 1 ) ;
}
}