给定一个二叉树,我想找出最大的子树是a BST就在其中。
此问题与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->data : max;
...
int currMin = (leftNodes == 0) ? p->data : min;
...
int currMax = (rightNodes == 0) ? p->data : max;
答案 0 :(得分:3)
请记住,此算法正在向下遍历树。访问节点的左子树后,以下情况之一为真:
min
类似地,在遍历右子树之后,当前树中的最大值是当前节点的值或右子树中的最大值(max
)
所以这一行
int currMin = (leftNodes == 0) ? p->data : min;
测试条件2或3是否为真,并相应地更新min
的值,以便该值对于测试树中当前节点上方的节点是正确的。