|
| 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 | +typedefstruct { |
| 37 | +intn; |
| 38 | +intmin; |
| 39 | +intmax; |
| 40 | +intflag; |
| 41 | +}val_t; |
| 42 | + |
| 43 | +val_tpost_order(structTreeNode*node,int*max) { |
| 44 | +val_tlval,rval,cval= {0 }; |
| 45 | + |
| 46 | +if (!node)returncval; |
| 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 | +returncval; |
| 68 | +} |
| 69 | + |
| 70 | +intlargestBSTSubtree(structTreeNode*root){ |
| 71 | +intmax=0; |
| 72 | + |
| 73 | +post_order(root,&max); |
| 74 | + |
| 75 | +returnmax; |
| 76 | +} |
| 77 | + |
| 78 | + |
| 79 | +/* |
| 80 | +Difficulty:Medium |
| 81 | +
|
| 82 | +
|
| 83 | +*/ |