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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/98.-validate-binary-search-tree-medium.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
