98 - Validate Binary Search Tree
Written on October 21, 2015
Tweet
Given a binary tree, determine if it is a valid binary search tree (BST).
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
public boolean isValidBST(TreeNode root) {
// write your code here
ArrayList<Integer> array = new ArrayList<Integer>();
inorderTraversal(array, root);
for(int i = 0; i < array.size() - 1; i++){
if (array.get(i) >= array.get(i+1)) return false;
}
return true;
}
public void inorderTraversal(ArrayList<Integer> array, TreeNode root){
if(root == null) return;
inorderTraversal(array, root.left);
array.add(root.val);
inorderTraversal(array, root.right);
}
}
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
stack = []
prev = None
while root or stack:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
#prev might be 0, so cannot use if prev here
if prev and root.val <= prev.val:
return False
prev = root
root = root.right
return True