• [Locked] Largest BST Subtree


    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.

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

      分析:

        典型树上的动态规划

      代码:

      //返回pair中4个值分别代表:是否是BST,BST的节点数,左边界,右边界
      pair<pair<bool, int>, pair<int, int>> dfs(TreeNode *cur, int pval, int &maxl) {
          pair<int, int> initp(pval, pval);
          //为NULL,则返回真,两端值设为父节点的值便于下一步计算
          if(!cur)
              return make_pair(make_pair(true, 0), initp);
          //进行下一层遍历
          pair<pair<bool, int>, pair<int, int>> leftp, rightp;
          leftp = dfs(cur->left, cur->val, maxl);
          rightp = dfs(cur->right, cur->val, maxl);
          //判断是否为BST
          if(leftp.first.first && rightp.first.first && cur->val >= leftp.second.second && cur->val <= rightp.second.first) {
              int curlen = leftp.first.second + 1 + rightp.first.second;
              maxl = max(maxl, curlen);
              return make_pair(make_pair(true, curlen), make_pair(leftp.second.first, rightp.second.second));
          }
          return make_pair(make_pair(false, 0), initp);
      }
      int largestSubtree(TreeNode *root) {
          int maxl = INT_MIN;
          dfs(root, 0, maxl);
          return maxl;
      }
    1. 相关阅读:
      nginx 平滑升级和location配置案例
      nginx
      基于zabbix的监控keepalive脑裂
      KVM部署
      基于keepalived的lvs负载均衡http集群
      高可用keepalived
      KVM
      无向图中 生成树,完全图,连通图 的区别
      java中 is
      第一章——软件工程学概述 思维导图
    2. 原文地址:https://www.cnblogs.com/littletail/p/5222460.html
    Copyright © 2020-2023  润新知