zoukankan      html  css  js  c++  java
  • [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. 相关阅读:
      Unity 5.3 Assetbundle热更资源
      自定义协同程序:CustomYieldInstruction
      C# 温故而知新: 线程篇(四)
      C# 温故而知新: 线程篇(三)
      C# 温故而知新: 线程篇(二)
      c# 温故而知新: 线程篇(一)
      C# 温故而知新:Stream篇(六)
      C# 温故而知新:Stream篇(七)
      C# 温故而知新:Stream篇(四)
      Redis高级数据类型
    2. 原文地址:https://www.cnblogs.com/littletail/p/5222460.html
    Copyright © 2011-2022 走看看