LeetCode 333. Largest BST Subtree
2016-05-26 01:59
429 查看
I am absolutely not good at bottom-up traversal.
/* 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. */ int largestBSTSubtree(TreeNode* root) { int mmin; int mmax; int nodes = 0; helper(root, mmin, mmax, nodes); return nodes; } bool helper(TreeNode* root, int& mmin, int& mmax, int nodes) { if(!root) return true; int lMin = INT_MAX; int lMax = INT_MIN; int lNode = 0; auto lValid = helper(root->left, lMin, lMax, lNode); int rMin = INT_MAX; int lMax = INT_MIN; int rNode = 0; auto rValid = helper(root->right, rMin, rMax, rNode); if(lValid == false || rValid == false || root->val <= lMin || root->val >= rMax) { nodes = max(lNode, rNode); return false; } mmin = min(lMin, root->val); mmax = max(rMax, root->val); nodes = lNode + rNode + 1; return true; }
相关文章推荐
- 深入浅出 - Android系统移植与平台开发(十三) - Sensor HAL框架分析之三
- 深入浅出 - Android系统移植与平台开发(十四) - Sensor HAL框架分析之四
- 深入浅出 - Android系统移植与平台开发(十二) - Sensor HAL框架分析之二
- LeetCode 144. Binary Tree Preorder Traversal(二叉树前缀遍历)
- 深入浅出 - Android系统移植与平台开发(十一) - Sensor HAL框架分析之一
- SQL注入式攻击
- HDOJ/HDU 1087 Super Jumping! Jumping! Jumping!(经典DP~)
- HDOJ/HDU 1087 Super Jumping! Jumping! Jumping!(经典DP~)
- Eclipse工具安装OpenExplorer插件--快速打开文档目录
- iOS开发之点触textView编辑区关闭键盘
- HashMap深度解析(二)
- 写了一个基于React+Redux的仿Github进度条
- Codeforces Round #354 (Div. 2)_Vasya and String(尺取法)
- Codeforces Round #354 (Div. 2)_Vasya and String(尺取法)
- Activity启动模式
- HashMap深度解析(一)
- webapi+entityframework分享
- jQuery基础(一)
- Struts2的convention插件,在步骤中使用Action注解跳转到其他jsp页面
- LeetCode 145. Binary Tree Postorder Traversal(二叉树后序遍历)