Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 031db83

Browse files
author
Victor
authored
initial version.
1 parent 20bdd34 commit 031db83

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

‎333. Largest BST Subtree.c

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
333. Largest BST Subtree
3+
4+
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.
5+
6+
Note:
7+
A subtree must include all of its descendants.
8+
9+
Example:
10+
11+
Input: [10,5,15,1,8,null,7]
12+
13+
10
14+
/ \
15+
5 15
16+
/ \ \
17+
1 8 7
18+
19+
Output: 3
20+
Explanation: The Largest BST Subtree in this case is the highlighted one.
21+
The return value is the subtree's size, which is 3.
22+
23+
24+
Follow up:
25+
Can you figure out ways to solve it with O(n) time complexity?
26+
*/
27+
28+
/**
29+
* Definition for a binary tree node.
30+
* struct TreeNode {
31+
* int val;
32+
* struct TreeNode *left;
33+
* struct TreeNode *right;
34+
* };
35+
*/
36+
typedef struct {
37+
int n;
38+
int min;
39+
int max;
40+
int flag;
41+
} val_t;
42+
43+
val_t post_order(struct TreeNode *node, int *max) {
44+
val_t lval, rval, cval = { 0 };
45+
46+
if (!node) return cval;
47+
48+
lval = post_order(node->left, max);
49+
rval = post_order(node->right, max);
50+
51+
if (lval.n == -1 || rval.n == -1 || // left or right is not a BST
52+
(lval.flag && node->val <= lval.max) || // current does not qualify a BST
53+
(rval.flag && node->val >= rval.min)) {
54+
cval.n = -1;
55+
} else {
56+
cval.n = lval.n + rval.n + 1; // current qualifies a BST
57+
58+
if (*max < cval.n) *max = cval.n;
59+
60+
cval.min = lval.flag == 0 ? node->val : lval.min;
61+
cval.max = rval.flag == 0 ? node->val : rval.max;
62+
cval.flag = 1;
63+
}
64+
65+
//printf("%d: %d,%d,%d\n", node->val, cval.min, cval.max, cval.n);
66+
67+
return cval;
68+
}
69+
70+
int largestBSTSubtree(struct TreeNode* root){
71+
int max = 0;
72+
73+
post_order(root, &max);
74+
75+
return max;
76+
}
77+
78+
79+
/*
80+
Difficulty:Medium
81+
82+
83+
*/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /