返回介绍

solution / 0300-0399 / 0333.Largest BST Subtree / README_EN

发布于 2024-06-17 01:04:02 字数 5492 浏览 0 评论 0 收藏 0

333. Largest BST Subtree

中文文档

Description

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.

 

Example 1:

Input: root = [10,5,15,1,8,null,7]
Output: 3
Explanation: The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3.

Example 2:

Input: root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1]
Output: 2

 

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -104 <= Node.val <= 104

 

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

Solutions

Solution 1

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def largestBSTSubtree(self, root: Optional[TreeNode]) -> int:
    def dfs(root):
      if root is None:
        return inf, -inf, 0
      lmi, lmx, ln = dfs(root.left)
      rmi, rmx, rn = dfs(root.right)
      nonlocal ans
      if lmx < root.val < rmi:
        ans = max(ans, ln + rn + 1)
        return min(lmi, root.val), max(rmx, root.val), ln + rn + 1
      return -inf, inf, 0

    ans = 0
    dfs(root)
    return ans
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *   TreeNode() {}
 *   TreeNode(int val) { this.val = val; }
 *   TreeNode(int val, TreeNode left, TreeNode right) {
 *     this.val = val;
 *     this.left = left;
 *     this.right = right;
 *   }
 * }
 */
class Solution {
  private int ans;

  public int largestBSTSubtree(TreeNode root) {
    ans = 0;
    dfs(root);
    return ans;
  }

  private int[] dfs(TreeNode root) {
    if (root == null) {
      return new int[] {Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
    }
    int[] left = dfs(root.left);
    int[] right = dfs(root.right);
    if (left[1] < root.val && root.val < right[0]) {
      ans = Math.max(ans, left[2] + right[2] + 1);
      return new int[] {
        Math.min(root.val, left[0]), Math.max(root.val, right[1]), left[2] + right[2] + 1};
    }
    return new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 0};
  }
}
/**
 * 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 {
public:
  int ans;

  int largestBSTSubtree(TreeNode* root) {
    ans = 0;
    dfs(root);
    return ans;
  }

  vector<int> dfs(TreeNode* root) {
    if (!root) return {INT_MAX, INT_MIN, 0};
    auto left = dfs(root->left);
    auto right = dfs(root->right);
    if (left[1] < root->val && root->val < right[0]) {
      ans = max(ans, left[2] + right[2] + 1);
      return {min(root->val, left[0]), max(root->val, right[1]), left[2] + right[2] + 1};
    }
    return {INT_MIN, INT_MAX, 0};
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func largestBSTSubtree(root *TreeNode) int {
  ans := 0
  var dfs func(root *TreeNode) []int
  dfs = func(root *TreeNode) []int {
    if root == nil {
      return []int{math.MaxInt32, math.MinInt32, 0}
    }
    left := dfs(root.Left)
    right := dfs(root.Right)
    if left[1] < root.Val && root.Val < right[0] {
      ans = max(ans, left[2]+right[2]+1)
      return []int{min(root.Val, left[0]), max(root.Val, right[1]), left[2] + right[2] + 1}
    }
    return []int{math.MinInt32, math.MaxInt32, 0}
  }
  dfs(root)
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文