Validate Binary Search Tree total accepted: 23828 total submissions: 91943my submissions
Given a binary tree, determine if it is a valid Binary Search Tree (BST ).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right Subtrees must also be binary search trees.
Give a binary tree and determine whether it is a valid binary tree.
Train of Thought: DFS
The valid binary search tree must meet the following conditions:
1. The left and right subtree are both valid binary search trees.
2. the rightmost leaf node of the Left subtree <root <leftmost leaf node of the right subtree
Complexity: time O (N), Space O (log n)
bool isValidBST(TreeNode *root) {if(!root) return true;TreeNode *right_most = root->left, *left_most = root->right;while(right_most && right_most->right){right_most = right_most->right;}while(left_most && left_most->left){left_most = left_most->left;}return isValidBST(root->left) && isValidBST(root->right)&& (!right_most || right_most->val < root->val)&& (!left_most || root->val < left_most->val);}
Leetcode DFS validate Binary Search Tree