二叉树——套路化解题--1.最大搜索二叉子树

求整棵树的xxx,假设以将个结点为头,它的xxx是什么,把它的可能的信息收集起来,就得到所有结点为头的xxx结果,那么答案肯定在其中。

 可能性来自  1.单独的左边,2.单独的右边,3.或者它们俩配合的结果

给定一棵二叉树的头节点head, 请返回最大搜索二叉子树的大小 

本题目中,以每个结点为头结点,它的最大搜索二叉树是什么,那么需要的信息

如以某个结点X为例,它的二叉搜索子树的可能性

可能性1.最大搜索二叉树来自X的左子树

可能性2.最大搜索二叉树来自X的右子树

3.左子树和右子树整体都是搜索二叉树,并且左子树的最大值小于X,右子树的最小值大于X,则以X为头结点的整棵二叉树都是搜索二叉树

利用递归,遍历每一个结点,然后从其左右子树上分别收集信息,来辅助判断当前结点的最大搜索二叉子树的信息

需要的信息:

1.左子树上最大二叉搜索子树的大小

2.右子树上最大二叉搜索子树的大小

3.左子树的最大二叉搜索树的头结点

4.右子树的最大二叉搜索树的头结点

5.左子树的最大值

6.右子树的最小值

简化信息:子树中二叉搜索子树的大小,子树中二叉搜索子树的头结点,子树的最大值,最小值。

返回值类型如下:

 public static class ResultType {
        int size;
        Tree head;
        int maxValue;
        int minValue;

        public ResultType(int size, Tree head, int maxValue, int minValue) {
            this.size = size;
            this.head = head;
            this.maxValue = maxValue;
            this.minValue = minValue;
        }
    }

  

package binaryTree.application;

/**
 * Created by Skye on 2018/5/4.
 * 给定一棵二叉树的头节点head, 请返回最大搜索二叉子树的大小
 *
 * 递归求解:
 * 计算每个结点左右子树的最大二叉搜索子树,并且进行判断,然后把该结点放到里面,
 * 看满不满足题意,如果满足题意,则加入,否则,返回左右子树中满足题意的子树信息
 */
public class BiggestSubBSTInTree {

    public static class ResultType {
        int size;
        Tree head;
        int maxValue;
        int minValue;

        public ResultType(int size, Tree head, int maxValue, int minValue) {
            this.size = size;
            this.head = head;
            this.maxValue = maxValue;
            this.minValue = minValue;
        }
    }

    public static ResultType search(Tree node){
        if(node == null){
            return new ResultType(0, null, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }

        ResultType left = search(node.left);
        ResultType right = search(node.right);

        int leftSize = left.size;
        int rightSize = right.size;

        int includeItSelf = 0;
        if(left.head == node.left && right.head == node.right
                && left.maxValue < node.val && right.minValue > node.val){
            includeItSelf = leftSize + rightSize + 1;
        }

        int maxSize = Math.max(Math.max(leftSize, rightSize), includeItSelf);
        Tree maxHead = leftSize > rightSize ? left.head : right.head;
        if(maxSize == includeItSelf){
            maxHead = node;
        }
        return new ResultType(maxSize,
                maxHead,
                Math.max(Math.max(left.maxValue, right.maxValue), node.val),
                Math.min(Math.min(left.minValue, right.minValue), node.val));
    }

    public static Tree biggestSubBSTInTree(Tree node){
        if(node == null){
            return node;
        }
        return search(node).head;
    }

}

  

原文地址:https://www.cnblogs.com/SkyeAngel/p/8990895.html