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的性质,左边的不能>= 右边的,那么就是一个inorder traverse
为什么用非递归更好?
如果用递归,我们是要用内存中的call-stack来做,它是一个size-limited memory area,如果调用很多很多次,容易stackOverFlow exception
但是用iteration做,使用数据结构中的stack,是在heap上,这样,在stack上消耗的空间是trivial的,我们不用change the total space consumption,而是把space consumption 从stack移到了heap上
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
pushLeft(stack, cur);
TreeNode pre = null;
while(!stack.isEmpty()) {
cur = stack.pop();
if(pre == null) {
pre = cur;
} else {
// pre != null;
if(pre.val >= cur.val) {
return false;
}
pre = cur;
}
if(cur.right != null) {
pushLeft(stack, cur.right);
}
}
return true;
}
private void pushLeft(Stack<TreeNode> stack, TreeNode cur) {
while(cur != null) {
stack.push(cur);
cur = cur.left;
}
}
}
思路2: 用traverse的方法, lower bound 和upper bound 来确定是否valid,注意参数需要使用用Long来表示,防止nodeval 本身就是Integer.MAX_VALUE, Integer.MIN_VALUE;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null) {
return true;
}
return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean dfs(TreeNode root, long minValue, long maxValue) {
if(root == null) {
return true;
}
if(root.val <= minValue || root.val >= maxValue) {
return false;
}
return dfs(root.left, minValue, root.val) && dfs(root.right, root.val, maxValue);
}
}