> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/98.-validate-binary-search-tree-medium.md).

# 98. Validate Binary Search Tree

## 1.問題

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

![](/files/-LI6aegv6LPbIH8pa-Zo)

## 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

![](/files/-LI6cDCFPbd94DoKoytw)
