LeetCode 333. Largest BST Subtree

本文介绍了一种查找二叉树中最大二叉搜索树子树的方法,并提供了详细的递归算法实现。通过递归检查每个节点及其左右子树,确保子树符合二叉搜索树的定义。

I am absolutely not good at bottom-up traversal.

/*
  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.
*/

int largestBSTSubtree(TreeNode* root) {
  int mmin;
  int mmax;
  int nodes = 0;
  helper(root, mmin, mmax, nodes);
  return nodes;
}

bool helper(TreeNode* root, int& mmin, int& mmax, int nodes) {
  if(!root) return true;
  int lMin = INT_MAX;
  int lMax = INT_MIN;
  int lNode = 0;
  auto lValid = helper(root->left, lMin, lMax, lNode);
  int rMin = INT_MAX;
  int lMax = INT_MIN;
  int rNode = 0;
  auto rValid = helper(root->right, rMin, rMax, rNode);
  if(lValid == false || rValid == false || root->val <= lMin || root->val >= rMax) {
    nodes = max(lNode, rNode);
    return false;
  }
  mmin = min(lMin, root->val);
  mmax = max(rMax, root->val);
  nodes = lNode + rNode + 1;
  return true;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值