题目:
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
来源:https://www.cnblogs.com/panini/p/6834491.html