题目
找到二叉树中最大搜索二叉树
java代码
package com.lizhouwei.chapter3;
/**
* @Description:找到二叉树中最大搜索二叉树
* @Author: lizhouwei
* @CreateDate: 2018/4/14 20:39
* @Modify by:
* @ModifyDate:
*/
public class Chapter3_7 {
public Node biggestSubBST(Node head) {
int[] record = new int[3];
return postOrder(head, record);
}
public Node postOrder(Node head, int[] record) {
if (head == null) {
record[0] = 0;
record[1] = Integer.MAX_VALUE;//子树最小值
record[2] = Integer.MIN_VALUE;//子树最大值
return null;
}
int value = head.value;
Node left = postOrder(head.left, record);
int leftSize = record[0];
int leftMin = record[1];
int leftMax = record[2];
Node right = postOrder(head.right, record);
int rightSize = record[0];
int rightMin = record[1];
int rightMax = record[2];
record[1] = Math.min(leftMin, value);
record[2] = Math.max(rightMax, value);
if (left == head.left && right == head.right && leftMax < value && value < rightMin) {
record[0] = leftSize + rightSize + 1;
return head;
}
record[0] = Math.max(leftSize, rightSize);
return leftSize > rightSize ? left : right;
}
//测试
public static void main(String[] args) {
Chapter3_7 chapter = new Chapter3_7();
Node head = new Node(6);
head.left = new Node(1);
head.right = new Node(12);
head.left.left = new Node(0);
head.left.right = new Node(3);
head.right.left = new Node(10);
head.right.right = new Node(13);
head.right.left.left = new Node(4);
head.right.left.right = new Node(14);
head.right.right.left = new Node(20);
head.right.right.right = new Node(16);
head.right.left.left.left = new Node(2);
head.right.left.left.right = new Node(5);
head.right.left.right.left = new Node(11);
head.right.left.right.right = new Node(15);
Node subHead = chapter.biggestSubBST(head);
NodeUtil.inOrder(subHead);
}
}