diff --git a/Leetcode/98/ysuh/README.md b/Leetcode/98/ysuh/README.md new file mode 100644 index 0000000..b82ae73 --- /dev/null +++ b/Leetcode/98/ysuh/README.md @@ -0,0 +1,12 @@ +## Link +[Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) + +## Topic +- Tree +- Recursion + +## Approach +We shrink the left & right available range while traversing down the tree with recursive call + +## Note +All the leaves at the left should be smaller than the parent and at the right should be greater than the parent. diff --git a/Leetcode/98/ysuh/solution.cpp b/Leetcode/98/ysuh/solution.cpp new file mode 100644 index 0000000..9622cc2 --- /dev/null +++ b/Leetcode/98/ysuh/solution.cpp @@ -0,0 +1,29 @@ +/** + * 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 { +private: + long int left_max_ = LONG_MAX; + long int right_min_ = LONG_MIN; + bool treeWalker(TreeNode* parent, long int left_max, long int right_min) { + if(parent == NULL) return true; + if(parent->val >= left_max || parent->val <= right_min){ + return false; + } + return treeWalker(parent->left, parent->val, right_min) && treeWalker(parent->right, left_max ,parent->val); + } + +public: + bool res = true; + bool isValidBST(TreeNode* root) { + return treeWalker(root, left_max_, right_min_); + } +};