首页 > 数据库 >[Oracle] LeetCode 333 Largest BST Subtree

[Oracle] LeetCode 333 Largest BST Subtree

时间:2022-08-18 17:25:29浏览次数:59  
标签:right TreeNode val BST Subtree 333 return root left

Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes.

A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties:

  • The left subtree values are less than the value of their parent (root) node's value.
  • The right subtree values are greater than the value of their parent (root) node's value.

Note: A subtree must include all of its descendants.

Solution

我们第一需要判断当前树是不是 \(BST\), 第二个就是求当前树的节点个数。

  • \(BST\): 用 \(dfs\) 来判断是不是 \(BST\), 对于左子树,其 \(Max=root.val\);而对于右子树,其\(Min=root.val\)
  • \(count\): 如果没节点,返回 \(0\); 否则递归的方式为:

\[1+count(root.left)+count(root.right) \]

所以在主程序中,我们依旧使用递归即可

点击查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    bool check(TreeNode* root, int Min, int Max){
        if(!root) return true;
        if(root->val <=Min || root->val>=Max){
            return false;
        }
        return check(root->left, Min, root->val) && check(root->right, root->val, Max);
    }
    
    int cnt(TreeNode* root){
        if(!root)return 0;
        return 1+cnt(root->left)+cnt(root->right);
    }
    
    
public:
    int largestBSTSubtree(TreeNode* root) {
        if(!root) return 0;
        if(check(root, INT_MIN, INT_MAX))return cnt(root);
        return max(largestBSTSubtree(root->left), largestBSTSubtree(root->right));
    }
};

标签:right,TreeNode,val,BST,Subtree,333,return,root,left
From: https://www.cnblogs.com/xinyu04/p/16599417.html

相关文章

  • binary search tree(bst)
    什么是bst?bst树,通常称为二叉搜索树,又叫二叉排序树,bst是一种特殊的二叉树结构,也是一种常见的数据结构类型,其中,bst很明显的特性是根节点大于左子树的节点小于右子树的节点,......
  • 459.repeated-substring-pattern 重复的子串
    假设一个字符串,是由一个重复的子串组成的,那么它的最长相等前后缀必然与整个字符串的必然相差了一个重复子串的长度。假设整个字符串的长度为len,那么next[len-1]+1就是......
  • 自学java第天之obstract抽象类
    父类中,写了抽象方法:什么是抽象方法:publicobstractvoid方法(){},::::::::::::::::::;只有方法名字,没有方法实现那么如果有个类想要继承定义的这个抽象类,那么就要重写父......
  • 159. Longest Substring with At Most Two Distinct Characters
    Givenastring s ,findthelengthofthelongestsubstring t  thatcontains atmost 2distinctcharacters.Example1:Input:"eceba"Output:3Explanat......
  • WebStrom开发微信小程序,基本配置
    WebStrom开发微信小程序,基本配置注意默认情况下,webstorm不支持wxml和wxss的文件类型,所以需要手动去配置。我们只需要配置.wxml和.wxss:识别为:.wxml->html.wxss->css......