首页 > 代码库 > 98. Validate Binary Search Tree
98. Validate Binary Search Tree
题目:
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.
链接:http://leetcode.com/problems/validate-binary-search-tree/
5/9/2017
算法班
自己之前没做出来,参考的别人答案。
思路:用in-order traversal判断是否是BST
1 public class Solution { 2 TreeNode lastNode; 3 public boolean isValidBST(TreeNode root) { 4 if (root == null) return true; 5 if (!isValidBST(root.left)) return false; 6 if (lastNode != null && lastNode.val >= root.val) return false; 7 lastNode = root; 8 if (!isValidBST(root.right)) return false; 9 return true; 10 } 11 }
iterative的写法,不需要全局变量
三种tree traversal,敲黑板
1 public class Solution { 2 public boolean isValidBST(TreeNode root) { 3 // Just use the inOrder traversal to solve the problem. 4 if (root == null) { 5 return true; 6 } 7 8 Stack<TreeNode> s = new Stack<TreeNode>(); 9 TreeNode cur = root; 10 TreeNode prev = null; 11 12 while (cur != null || !s.empty()) { 13 while (cur != null) { 14 s.push(cur); 15 cur = cur.left; 16 } 17 cur = s.pop(); 18 if (prev != null && prev.val >= cur.val) return false; 19 prev = cur; 20 cur = cur.right; 21 } 22 return true; 23 } 24 }
有些其他人的算法是传入long.MAX_VALUE, long.MIN_VALUE来判断的,我认为算是cheat吧,至少需要知道不使用这种trick的方法。
更多讨论:
https://discuss.leetcode.com/category/106/validate-binary-search-tree
98. Validate Binary Search Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。