Largest BST Subtree
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.
Note:
A subtree must include all of its descendants.
Here's an example:
10 / 5 15 / 1 8 7
The Largest BST Subtree in this case is the highlighted one.
The return value is the subtree's size, which is 3.
Follow up:
Can you figure out ways to solve it with O(n) time complexity?
分析:
典型树上的动态规划
代码:
//返回pair中4个值分别代表:是否是BST,BST的节点数,左边界,右边界 pair<pair<bool, int>, pair<int, int>> dfs(TreeNode *cur, int pval, int &maxl) { pair<int, int> initp(pval, pval); //为NULL,则返回真,两端值设为父节点的值便于下一步计算 if(!cur) return make_pair(make_pair(true, 0), initp); //进行下一层遍历 pair<pair<bool, int>, pair<int, int>> leftp, rightp; leftp = dfs(cur->left, cur->val, maxl); rightp = dfs(cur->right, cur->val, maxl); //判断是否为BST if(leftp.first.first && rightp.first.first && cur->val >= leftp.second.second && cur->val <= rightp.second.first) { int curlen = leftp.first.second + 1 + rightp.first.second; maxl = max(maxl, curlen); return make_pair(make_pair(true, curlen), make_pair(leftp.second.first, rightp.second.second)); } return make_pair(make_pair(false, 0), initp); } int largestSubtree(TreeNode *root) { int maxl = INT_MIN; dfs(root, 0, maxl); return maxl; }