1. // 返回值结构
    2. public static class ReturnData{
    3. public int max;
    4. public int min;
    5. public Boolean isBST;
    6. public ReturnData(int max, int min, Boolean isBST) {
    7. this.max = max;
    8. this.min = min;
    9. this.isBST = isBST;
    10. }
    11. }
    12. // 树形DP:先列出搜索树条件,然后向左树要信息,向右树要信息,罗列可能性。
    13. // 条件: 左搜 右搜 左max<head 右min>head。四个条件都成立才是搜索二叉树
    14. // 要的信息:左是否是搜索二叉树,最大值。 右是否是搜索二叉树 ,最小值。
    15. // 递归返回值为 是否是搜索二叉树,最大值,最小值,要把左右要求的信息弄成合集。
    16. public static ReturnData IsBST(Node head){
    17. if(head == null){
    18. return null;
    19. }
    20. // 左树返回值
    21. ReturnData leftReturn = IsBST(head.left);
    22. // 右树返回值
    23. ReturnData rightReturn = IsBST(head.right);
    24. // 自己也要有返回值
    25. int min = head.value;
    26. int max = head.value;
    27. // 设置自己min max
    28. if(leftReturn != null){
    29. min = Math.min(min,leftReturn.min);
    30. max = Math.max(max, leftReturn.max);
    31. }
    32. if(rightReturn != null){
    33. min = Math.min(min,rightReturn.min);
    34. max = Math.max(max,rightReturn.max);
    35. }
    36. boolean isBST = true;
    37. // 左树最大值大于头值 false
    38. // 左边必定达标,只有两边都达标才是false
    39. if(leftReturn !=null && ( !leftReturn.isBST || leftReturn.max >= head.value)){
    40. isBST = false;
    41. }
    42. // 右树最小值小于头值 false
    43. if(rightReturn !=null && (!rightReturn.isBST || rightReturn.min <= head.value)){
    44. isBST = false;
    45. }
    46. return new ReturnData(max,min,isBST);
    47. }