leetcode#98. Validate Binary Search Tree
来源:互联网 发布:去马赛克的软件 编辑:程序博客网 时间:2024/06/16 14:09
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.
Code
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if root == None: return True elif root.left != None and root.left.val >= root.val: return False elif root.right != None and root.right.val <= root.val: return False else: return self.recur(root.left, float("-inf"), root.val) and self.recur(root.right, root.val, float("inf")) def recur(self, node, Min, Max): if node == None: return True elif node.val <= Min or node.val >= Max: return False else: return self.recur(node.left, Min, node.val) and self.recur(node.right, node.val, Max)
用最大最小值的方法限定后续的节点值,始终将后续的节点值限制在一定的区间内,同时避免了每次判断节点值时得从根节点开始判断。缺点时最大最小值是个特例,当节点中有值为inf或-inf时该算法失效。
Code2(author:jakwings)
class Solution {public: bool isValidBST(TreeNode* root) { TreeNode* prev = NULL; return validate(root, prev); } bool validate(TreeNode* node, TreeNode* &prev) { if (node == NULL) return true; if (!validate(node->left, prev)) return false; if (prev != NULL && prev->val >= node->val) return false; prev = node; return validate(node->right, prev); }};
注意这里的prev为引用调用,所以prev的值一直在改变,总的来说code2不仅仅可以用于判断BST,它可以用于所有前序遍历的操作中,值得学习。
Conclusion
学习了一种通用的树遍历方法,值得记下来
阅读全文
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
- 单例模式
- android向服务器请求数据框架
- 初识Lucene(1)
- reset.css
- 278. First Bad Version
- leetcode#98. Validate Binary Search Tree
- Java集合HashMap的源码解刨
- 设计模式之策略模式(STRATEGY)
- 数据结构之顺序队列和链式队列常用的一些操作
- 腾讯js面试题2
- 结构化数据上的机器学习大杀器XGBoost
- 百练 8462:大盗阿福
- c++容易混淆的概念
- 英语发音困难点记录