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 is binary search trees.
BOOL Isvalidbst (treenode* root) {///To determine if a binary tree is a balance binary tree//The left child should be smaller than the Father node in the first balanced binary tree//any node should be greater than the Father node//The maximum value of the left subtree of any node should be less than it The minimum value of the right subtree of any node should be greater than it if (null==root) return true; treenode* behind=root->right;while (behind && behind->left) behind=behind->left; treenode* Ahead=root->left;while (ahead && Ahead->right) ahead=ahead->right;//left and right subtree are not empty if (behind && ahead) {if (Behind->val > Root->val && ahead->val < Root->val) {if (root->left- >val < Root->val && root->right->val > Root->val) return Isvalidbst (Root->left) & & Isvalidbst (root->right); Elsereturn false;} Elsereturn false;} The right subtree is not empty if (behind) {if (Behind->val > Root->val && root->right->val > Root->val) return Isvalidbst (root->right); Elsereturn false;} Left dial hand tree is not empty if (ahead) {if (Ahead->val < root->val && Root->left->val < Root->val) return Isvalidbst (Root->left); Elsereturn false;} Case of the left and right subtree are empty reTurn true;}
Leetcode (+): Validate Binary Search Tree