# 98. Validate Binary Search Tree

[Link](https://leetcode.com/problems/validate-binary-search-tree/submissions/)

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

Input: [2,1,3]
Output: true
```

**Example 2:**

```
    5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
```

**Solution**

Note: Equal case is not acceptable.

Way 1: 比較直覺，當掌握了inorder travelsa之後，這已透過這個方式檢查是否順序正確。

T: O(N)

```
class Solution {
    public boolean isValidBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        boolean ret = true;
        TreeNode prev = null;
        while(root != null||!stack.isEmpty()){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if(prev != null && prev.val >= root.val){
                ret = false;
                break;
            }
            prev = root;
            root = root.right;
        }
        return ret;
    }
}
```

Way 2 : 使用recursion的方式去判node.left 跟 node.right

T: O(N)

條件除了node.left.val < node.val && node.righ.val > node.val之外，

要額外判斷node.left內的所有子node都要比node.val小，同理node.righ內的所有子node都要比node.val大

所以設計遞迴function時，多了上下限(maxValue, minValue)的概念\
對左子樹而言，上限是parent node.val, 下限則是沿用parent node的下限\
對右子樹而言，上限是parent node上限, 下限則是parent node.val

```
     public boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    
    public boolean isValidBST(TreeNode root, long minVal, long maxVal) {
        if (root == null) return true;
        if (root.val >= maxVal || root.val <= minVal) return false;
        return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);
    }
```
