[LeetCode]98. Validate Binary Search Tree
来源:互联网 发布:未来造价软件 编辑:程序博客网 时间:2024/06/06 20:56
Description:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Example 1:
2 / \ 1 3
Binary tree [2,1,3]
, return true.Example 2:
1 / \ 2 3
Binary tree [1,2,3]
, return false.———————————————————————————————————————————————————
Solution:
题意:判断给定的二叉搜索树是否合法(满足以上三点规则)。
思路:
第一种方法:根据中序遍历的特性(左子数->根节点->右子树),恰好与搜索树特性相匹配(左子数<根节点<右子树)。因此我们可以将中序遍历的结果输入到一个数组中,然后检查该数组是否按增序排列,如果不是则false,否则true。
但这种方法依赖的规则是less than或greater than,也就是说父亲节点与孩子节点间没有等于的关系。如果题目改为 not greater than 或 not less than,那么该方法就不适用了。因为它分不清以下两种树的区别:
第二种方法:依然利用中序遍历的特性,用递归的方法保存前驱节点,每次找到新的节点判断前驱节点与当前节点的关系即可。值得注意的是递归函数中传前驱节点时应该按址传递,即及时更新前驱节点信息,否则无法进行比对。
/** * 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) { TreeNode* forwardNode = NULL; return validateBST(root, forwardNode); } // 按址传递 bool validateBST(TreeNode* r, TreeNode*& f) { if (r == NULL) return true; bool left = validateBST(r->left, f); if (f != NULL && r->val <= f->val) return false; f = r; return left && validateBST(r->right, f); }};
第三种方法:设置最大值和最小值,每次访问一个新的节点后对比当前值是否小于最小值或大于最大值,若不超过则访问下一个并将最大值最小值更新(访问左子树更新最大值,访问右子树更新最小值),否则false。不过这种方法现在在LeetCode上已经失效,因为现在的测试用例多了INT_MIN和INT_MAX,算法无法检测。而且这种方法思路比较简单,没有达到题目原意(锻炼加深对二叉树性质的理解),因此我还是推荐第二种方法,这里也只贴出了第二种方法代码~
阅读全文
0 0
- LeetCode 98. Validate Binary Search Tree
- [LeetCode]98.Validate Binary Search Tree
- [Leetcode] 98. Validate Binary Search Tree
- LeetCode --- 98. Validate Binary Search Tree
- [leetcode] 98.Validate Binary Search Tree
- [leetcode] 98.Validate Binary Search Tree
- [Leetcode] 98. Validate Binary Search Tree @python
- Leetcode 98. Validate Binary Search Tree
- [LeetCode]98. Validate Binary Search Tree
- leetcode 98. Validate Binary Search Tree
- *LeetCode 98. Validate Binary Search Tree
- 98. Validate Binary Search Tree LeetCode
- LeetCode 98. Validate Binary Search Tree
- LeetCode 98. Validate Binary Search Tree
- LeetCode *** 98. Validate Binary Search Tree
- 98. Validate Binary Search Tree-leetcode-java
- [leetcode] 98. Validate Binary Search Tree
- LeetCode - 98. Validate Binary Search Tree
- Spring Boot配置外置Tomcat和JSP视图教程(IntelliJ IDEA + Maven)
- 设计模式阅读备忘笔记-装饰模式
- 第四周 项目3
- fakerbaidu
- angulas.js 增删改查
- [LeetCode]98. Validate Binary Search Tree
- . 报错 specified child already has a parent. You must call removeView() on the child's parent first
- ngrx 初探
- 单链表
- 爬虫学习笔记1——爬取糗百段子
- [Go]hello world
- 字符串输入、输出
- HDU
- 从豆瓣电影评分算法说起