# 98. Validate Binary Search Tree

## 1.問題

* 給予一個binary tree, 判斷他是否是binary search tree
* binary search tree定義如下:
  * 左子樹只有一個root node, 且其值小於root node
  * 右子樹只有一個root node, 且其值大於root node
  * 左又子樹也是BST

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LI6E4weWHpk9d8EVzMT%2F-LI6aegv6LPbIH8pa-Zo%2F2018072301.jpg?alt=media\&token=d546a0dd-54dc-4169-b296-5cd357c4bc37)

## 2.想法&#x20;

* Binary search tree的特性是LVR, 因此如果用Inorder traversal走訪整個Binary search tree將會得到一個由小到大排列的序列
* 用一全域變數儲存前一次走訪的node, 與目前走訪到的的(V)相比

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool flag = false;
    int lastVal = 0;
    bool isValidBST(TreeNode* root) {
        if (!root) {
            return true;
        }
        
        if (!isValidBST(root->left)) {
            return false;
        }
        
        if (!flag) {
            flag = true;
        } else {
            if (root->val <= lastVal) {
                return false;
            }
        }
        lastVal = root->val;
        if (!isValidBST(root->right)) {
            return false;
        }
        
        return true;
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LI6E4weWHpk9d8EVzMT%2F-LI6cDCFPbd94DoKoytw%2F2018072302.jpg?alt=media\&token=fb60463f-e049-4f18-9ad2-90e8e809e5a3)
