Leetcode Note: Validate Binary Search Tree
I. Description
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.
Confused what "{1, #, 2, 3}" means?
Ii. Question Analysis
The main idea of this question is to determine whether a binary search tree is valid. This can be determined based on the definition of the binary search tree, that is, the value of an internal node must be greater than the maximum value of the Left subtree, the value must be smaller than the maximum value of the right subtree.
According to this definition, we can recursively determine that the time complexity of this method isO(n), The space complexity isO(logn). Note that you must remember to update the maximum and minimum values of the tree with the node as the parent node so that the previous call can be judged Upon Recursive return.
Iii. Sample Code
#include
struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution{private: bool isValidBST(TreeNode* root, int &MinValue, int &MaxValue) { if (!root) { return true; } if (root->left) { if (root->val <= root->left->val) { return false; } int LeftMinValue = 0; int LeftMaxValue = 0; if (!isValidBST(root->left, LeftMinValue, LeftMaxValue)) { return false; } else { MinValue = LeftMinValue; if (LeftMaxValue != LeftMinValue) { if (root->val <= LeftMaxValue) { return false; } } } } else { MinValue = root->val; } if (root->right) { if (root->val >= root->right->val) { return false; } int RightMinValue = 0; int RightMaxValue = 0; if (!isValidBST(root->right, RightMinValue, RightMaxValue)) { return false; } else { MaxValue = RightMaxValue; if (RightMaxValue != RightMinValue) { if (root->val >= RightMinValue) { return false; } } } } else { MaxValue = root->val; } return true; }public: bool isValidBST(TreeNode* root) { int MinValue = 0; int MaxValue = 0; bool IsLeaf = true; return isValidBST(root, MinValue, MaxValue); }};