Try   HackMD

98. Validate Binary Search Tree


My Solution

The Key Idea for Solving This Coding Question

C++ Code

/** * 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 isValidBST(TreeNode *root) { return isValidBST(root, LONG_MIN, LONG_MAX); } private: bool isValidBST(TreeNode *root, long lowerBound, long upperBound) { if (root == nullptr) { return true; } if (root->val <= lowerBound || upperBound <= root->val) { return false; } return isValidBST(root->left, lowerBound, root->val) && isValidBST(root->right, root->val , upperBound); } };

Time Complexity

O(n)
n
is the number of nodes in the binary tree referred by root.

Space Complexity

O(H)
H
is the height of the binary tree referred by root.

Miscellane