[leetcode] 333. Largest BST Subtree 解题报告

题目链接: https://leetcode.com/problems/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.
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.

Hint:

  1. You can recursively use algorithm similar to 98. Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity.

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


思路: 按照正常的top-down的思路就是依次判断当前结点为根的树是否为搜索二叉树, 这个并不难, 只要在向左右搜索的时候带一个范围即可. 这种方法的时间复杂度是O(n!), 因此对于很大的树将极为耗时. 但是如果用bottom-up的话将可将时间复杂度降为O(n), 这是一个极大的优化. 

现在来考虑一下bottom-up我们需要从子树获得哪些信息? 首先肯定是需要子树的范围, 因为我们要判断当前结点为根的树是否为二叉搜索树就要满足当前结点大于左子树的最大值, 小于右子树的最小值. 再次我们还需要知道子树是否为二叉搜索树以及其二叉搜索树的大小. 有了这些信息我们就可以判断以当前结点为根的二叉树是否为二叉搜索树了. 但是这题很容易写的比较复杂.

代码如下:

/**
 * 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:
    vector<int> DFS(TreeNode* root, int& ans)
    {
        if(!root) return vector<int>{0, INT_MAX, INT_MIN};
        auto left=DFS(root->left, ans), right=DFS(root->right, ans);
        if(root->val > left[2] && root->val < right[1])
        {
            int Min =min(root->val, left[1]), Max =max(root->val, right[2]);
            ans = max(ans, left[0] + right[0] + 1);
            return vector<int>{left[0] +right[0] +1, Min , Max};
        }
        return vector<int>{0, INT_MIN, INT_MAX};
    }
    
    int largestBSTSubtree(TreeNode* root) {
        int ans = 0;
        DFS(root, ans);
        return ans;
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值