[LeetCode][Tree] 333. Largest BST Subtree

Problem

More LeetCode Discussions

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.
Here's an example:

    10
    / \
   5  15
  / \   \ 
 1   8   7

The Largest BST Subtree in this case is the highlighted one.
The return value is the subtree's size, which is 3.

Solution

  1. 判斷是否是BST。對(duì)于當(dāng)前node左子樹(shù)最大節(jié)點(diǎn)值 < node.val,右子樹(shù)最小節(jié)點(diǎn)值 > node.val
  2. 計(jì)算數(shù)目。當(dāng)前節(jié)點(diǎn)的最大數(shù)目為左右子樹(shù)中最大的,如果左右子樹(shù)同時(shí)滿(mǎn)足都為BST,并且當(dāng)前節(jié)點(diǎn)的樹(shù)也滿(mǎn)足BST。則最大數(shù)目為leftSize + rightSize + 1。
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int largestBSTSize(TreeNode *node, int &minV, int &maxV, bool &isTree) {
        if (node == NULL) {
            isTree = true;
            return 0;
        }    
        
        int leftMaxV = INT_MIN;
        int leftMinV = INT_MAX;
        bool leftIsTree = true;
        int leftSize = largestBSTSize(node->left, leftMinV, leftMaxV, leftIsTree);
        
        int rightMinV = INT_MAX;
        int rightMaxV = INT_MIN;
        bool rightIsTree = true;
        int rightSize = largestBSTSize(node->right, rightMinV, rightMaxV, rightIsTree);
        
        int maxSize = max(leftSize, rightSize);
        
        if (leftMaxV < node->val && node->val < rightMinV && leftIsTree && rightIsTree) {
            maxSize = leftSize + rightSize + 1;
            isTree = true;
        } else {
            isTree = false;
        }
        
        maxV = max(max(leftMaxV, rightMaxV), node->val);
        minV = min(min(leftMinV, rightMinV), node->val);
        
        return maxSize;
    }
    
    int largestBSTSubtree(TreeNode* root) {
        int maxV;
        int minV;
        bool isTree;
        return largestBSTSize(root, minV, maxV, isTree);
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容