【leetcode】Validate Binary Search Tree 题解三种思路
来源:互联网 发布:吴达洙 知乎 编辑:程序博客网 时间:2024/06/03 17:12
https://leetcode.com/submissions/detail/39976412/
//2015-10-22 20:58:42 //1.中序 保存在一个vector中,检查是否有序//2.传递前驱指针,看是否有序//3.从底向上 ,开始只传递回最大值,不对,比如右侧应该传回最小值,因此改为两个返回值//2015-10-22 21:24:21/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isValidBST(TreeNode* root) { if(root == NULL){ return true; } int leftmin,rightmax = 0; return check(root,leftmin,rightmax); } bool check(TreeNode *root,int &leftmin,int &rightmax){ if(root == NULL){ return true; } leftmin = root->val; rightmax = root->val; if(root->left==NULL &&root->right==NULL){ return true; } int left,right; if(root->left != NULL){ if(check(root->left,left,right) == false || right>=root->val){ return false; } leftmin = left; } if(root->right != NULL){ if(check(root->right,left,right)==false || left<=root->val){ return false; } rightmax = right; } return true; } };
另外,还有一种是从顶向下的递归方法,每次把两个边界传递过来,初始值有问题,例如设为INT_MIN 或INT_MAX,如果测试用例中包含该值则出错。
0 0
- 【leetcode】Validate Binary Search Tree 题解三种思路
- LeetCode题解: Validate Binary Search Tree
- LeetCode题解:Validate Binary Search Tree
- LeetCode题解-98-Validate Binary Search Tree
- leetcode 题解 98. Validate Binary Search Tree
- LeetCode 98. Validate Binary Search Tree 题解
- leetcode之Validate Binary Search Tree解决思路
- LeetCode 题解(53): Validate Binary Search Tree
- LeetCode题解——Validate Binary Search Tree
- LeetCode Algorithms 98. Validate Binary Search Tree 题解
- LeetCode: Validate Binary Search Tree
- [Leetcode] Validate Binary Search Tree
- LeetCode : Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Validate binary search tree
- [LeetCode]Validate Binary Search Tree
- [Leetcode]Validate Binary Search Tree
- [leetcode]Validate Binary Search Tree
- Combination Sum III
- 开源网络框架Volley(3)
- 自定义导航栏的左右按钮
- 字符串的基本操作
- ViewPager的实现:动态添加RadioButton
- 【leetcode】Validate Binary Search Tree 题解三种思路
- 彻底解密C++宽字符:1、从char到wchar_t
- Eclipse快捷键大全
- 动态规划之0-1背包问题
- RSA算法原理
- java 建造者模式详解
- 开源框架Volley源码分析
- TextField 相关
- nginx配置域名重定向