12. Largest BST Subtree

Link to the problem

Description

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.

Example

Input: [10,5,15,1,8,null,7], Output: 3

Idea

Recursively compute the number of nodes, whether the current tree is a BST, the size of the largest BST subtree in the current tree, min value, and max value.

Solution

class Solution {
private:
    // info[0] stores size of largest BST subtree
    // info[1] stores whether the tree is BST
    // info[2] stores size of current tree
    // info[3] stores min
    // info[4] stores max
    void largestBSTSubtreeHelper(TreeNode *root, vector<int> &info) {
        if (!root) {
            info.push_back(0);
            info.push_back(1);
            info.push_back(0);
            info.push_back(INT_MAX);
            info.push_back(INT_MIN);
        } else {
            vector<int> leftInfo, rightInfo;
            largestBSTSubtreeHelper(root->left, leftInfo);
            largestBSTSubtreeHelper(root->right, rightInfo);
            int currSize = 1 + leftInfo[2] + rightInfo[2];
            int currMin = min(root->val, min(leftInfo[3], rightInfo[3]));
            int currMax = max(root->val, max(leftInfo[4], rightInfo[4]));
            bool isBST = leftInfo[1] > 0 && rightInfo[1] > 0;
            if (root->val <= leftInfo[4] || root->val >= rightInfo[3]) isBST = false;
            int largestBST = isBST ? currSize : max(leftInfo[0], rightInfo[0]);
            info.push_back(largestBST);
            info.push_back(isBST ? 1 : 0);
            info.push_back(currSize);
            info.push_back(currMin);
            info.push_back(currMax);
        }
    }

public:
    int largestBSTSubtree(TreeNode* root) {
        vector<int> info;
        largestBSTSubtreeHelper(root, info);
        return info[0];
    }
};

73 / 73 test cases passed.
Runtime: 12 ms

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 我突然想起,去南京考试那会儿。下了车走反了方向,南辕北辙 。考试学校侧面是一条狭窄的小路,路边停满了私家车,左右俩...
    金言儿阅读 321评论 0 0
  • 今天中午大家吃饭,结账的时候虞总问餐厅服务员他们智能POS机,有没有使用在线点单、在线定位的功能呀? 服务员,很奇...
    怪物办公室阅读 207评论 0 0
  • 每个人在他成长的过程当中 其实他内心是居住了一个小男孩的 那这个小男孩是什么意思呢 就是你很容易被这个世界上 任何...
    Humphrey_z阅读 428评论 0 0