[Leetcode] Validate Binary Search Tree
来源:互联网 发布:淘宝钻石买家号出售 编辑:程序博客网 时间:2024/06/07 22:52
题目:
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.
思路:中序遍历。中序遍历BST的顺序实际上是一个递增的序列,设置一个指针记录每一个node的前一个node,比较即可判断该BST的有效性。previous的赋值发生在遍历完左子树和当前节点值之后,遍历右子树之前。同时注意做好剪枝工作。
class Solution {public: TreeNode* previous = nullptr; //record the previous node of the current node bool inorder_traversal(TreeNode* root) { if (root == nullptr) return true; if (!inorder_traversal(root->left)) return false; //pruning, no need to go left if (previous != nullptr && previous->val >= root->val) return false; previous = root; //the current node becomes the previous node if (!inorder_traversal(root->right)) return false; //try the right branch else return true; } bool isValidBST(TreeNode *root) { return inorder_traversal(root); }};
总结:设置previous指针可以解决类似很多问题。复杂度为O(2^n).
0 0
- 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
- 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
- 【Leetcode】Validate Binary Search Tree
- 【leetcode】Validate Binary Search Tree
- WEB免费打印控件推荐
- 【网络爬虫】【python】网络爬虫(五):scrapy爬虫初探——爬取网页及选择器
- poj3107(树的重心)
- IE提示“Internet Explorer无法打开站点XX,已终止操作”的解决办法
- Catalan数(组合数学)
- [Leetcode] Validate Binary Search Tree
- Appium0.18.x迁移到Appium1.x须知事项(灰常有用,解答了本人几个疑问)
- 装饰者模式C++实现
- JQUERY+MYSQL+PHP通用用户注册页面的实例
- 电饭锅电饭锅电饭锅
- 导出数据到EXCEL文档
- Hibernate映射文件中的主键生成方式
- 一个程序员的苦衷
- swift版的uipagecontrol学习