# 98. Validate Binary Search Tree **筆記頁面:**[Leetcode 解題隨筆](https://hackmd.io/@yuto0226/H1EnKUxna) [98. Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) Difficulity:`Medium` Toptics:`Tree` `Depth-First Search` `Binary Search Tree` `Binary Tree` ## 解答 ### 解題思路 可以簡單統整二元搜尋樹的節點規律: * 節點數值範圍:$[l,r]$ * 父節點的範圍:$[l,r]$ * 父節點的值:$val$ * 左子節點值的範圍:$[l,val]$ * 右子節點值的範圍:$[val,r]$ 以此為判斷去比較該節點的值是否符合其應在的範圍。 ### 實作方式 另外寫一個`helper(TreeNode* root,long long l, long long r)`函式,將節點及其樹值的左右上限作為參數傳入,去遞迴比較節點的範圍。 ### 複雜度 時間複雜度:$O(n)$ >有幾個節點就要檢查多少次 空間複雜度: ### 程式碼 ```cpp /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), * right(right) {} * }; */ class Solution { public: bool helper(TreeNode* root,long long l, long long r) { if (!root) return true; int val = root->val; if (val <= l || val >= r) return false; return helper(root->left, l, val) && helper(root->right, val, r); } bool isValidBST(TreeNode* root) { if (!root->left && !root->right) return true; else return helper(root, -2147483649, 2147483648); } }; ```