LeetCode 333. Largest BST Subtree

Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.

Note:
A subtree must include all of its descendants.

 

Follow up:
Can you figure out ways to solve it with O(n) time complexity?

此题的意思是找出一棵二叉树里的最大二叉搜索树,即二叉树内的一棵最大的满足二叉搜索树性质的子树。

二叉搜索树的定义是:二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。

题解:

采用后序遍历,先计算出子树的解。对于每个子树,计算出的结果res是一个integer的长度为4的数组。res[0]:是否是二叉搜索树,res[1]该棵二叉搜索树的大小,res[2]该二叉搜索树的最小值,res[3]该二叉搜索树的最大值。

然后判断当前子树是否为二叉搜索树,当左子树,右子树不为二叉搜索树,或者左子树的最大值大于等于root的值,或者右子树的最小值小等于root的值时,当前子树不是二叉搜索树。

否则当前子树是二叉搜索树。

时间复杂度O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int largestBSTSubtree(TreeNode root) {
        if(root == null) return 0;
        Integer[] res = dfs(root);

        return res[1];
    }
    public Integer[] dfs(TreeNode root) {
        if(root == null) return new Integer[]{1, 0, null, null};
        if(root.left == null && root.right == null) return new Integer[]{1, 1, root.val, root.val};
        Integer[] left = dfs(root.left);
        Integer[] right = dfs(root.right);
        if(left[0] == 0 || right[0] == 0 || (left[3] != null && left[3] >= root.val) || (right[2] != null && right[2] <= root.val)) {
            return new Integer[]{0, Math.max(left[1], right[1]), null, null};
        }

        return new Integer[]{1, 1 + left[1] + right[1], left[2] == null ? root.val : left[2], right[3] == null ? root.val : right[3]};
        
        
    }
}

 

posted @ 2019-04-20 13:04  起点菜鸟  阅读(231)  评论(0编辑  收藏  举报