gpt4 book ai didi

algorithm - 二叉搜索树 (BST) 的最大子树

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:14:57 24 4
gpt4 key购买 nike

Given a binary tree, I want to find out the largest subtree which is a BST in it.

此问题与 Finding the largest subtree in a BST 重复,其中 1337c0d3r 通过自下而上遍历树给出 O(n) 解决方案。有两行代码让我感到困惑。谁能帮我解释一下?

// Find the largest BST subtree in a binary tree.
// If the subtree is a BST, return total number of nodes.
// If the subtree is not a BST, -1 is returned.
int findLargestBSTSubtree(BinaryTree *p, int &min, int &max,
int &maxNodes, BinaryTree *& largestBST) {
if (!p) return 0;
bool isBST = true;
int leftNodes = findLargestBSTSubtree(p->left, min, max, maxNodes, largestBST);
int currMin = (leftNodes == 0) ? p->data : min;
if (leftNodes == -1 ||
(leftNodes != 0 && p->data <= max))
isBST = false;
int rightNodes = findLargestBSTSubtree(p->right, min, max, maxNodes, largestBST);
int currMax = (rightNodes == 0) ? p->data : max;
if (rightNodes == -1 ||
(rightNodes != 0 && p->data >= min))
isBST = false;
if (isBST) {
min = currMin;
max = currMax;
int totalNodes = leftNodes + rightNodes + 1;
if (totalNodes > maxNodes) {
maxNodes = totalNodes;
largestBST = p;
}
return totalNodes;
} else {
return -1; // This subtree is not a BST
}
}

BinaryTree* findLargestBSTSubtree(BinaryTree *root) {
BinaryTree *largestBST = NULL;
int min, max;
int maxNodes = INT_MIN; // INT_MIN is defined in <climits>
findLargestBSTSubtree(root, min, max, maxNodes, largestBST);
return largestBST;
}

我被下面两行代码弄糊涂了。按照我的常识,递归遍历左树后,应该更新max变量,为什么要放int currMin = (leftNodes == 0)? p->data : min; 递归遍历左树后右?
int currMax = (rightNodes == 0) 同样的问题? p->数据:最大值;

...
int currMin = (leftNodes == 0) ? p->data : min;
...
int currMax = (rightNodes == 0) ? p->data : max;

最佳答案

请记住,此算法是自底向上遍历树。访问节点的左子树后,以下情况之一为真:

  1. 左子树不是 BST => 当前树不是 BST
  2. 左子树是 BST => 当前树中的最小值是 min
  3. 左子树没有节点=>当前树中的最小值为当前节点的值

同理,遍历右子树后,当前树中的最大值要么是当前节点的值,要么是右子树中的最大值(max)

所以这条线 int currMin = (leftNodes == 0) ? p->数据:最小值;测试条件 2 或 3 是否为真,并相应地更新 min 的值,以便该值对于测试树中当前节点上方的节点是正确的。

关于algorithm - 二叉搜索树 (BST) 的最大子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14512704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com