Skip to content

Commit

Permalink
Create validBinarySearchTree.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
anishmo99 committed Oct 18, 2020
1 parent d2b9640 commit 171787e
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions DFS/validBinarySearchTree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* 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 dfs(TreeNode *root, TreeNode *low, TreeNode *high)
{
if (!root)
return true;

if (low and root->val and root->val <= low->val)
return false;

if (high and root->val and root->val >= high->val)
return false;

return dfs(root->left, low, root) and dfs(root->right, root, high);
}

bool isValidBST(TreeNode *root)
{
return dfs(root, nullptr, nullptr);
}
};

0 comments on commit 171787e

Please sign in to comment.