[Simple Algorithm] 27. Verify Binary Search Tree

topic:

Given a binary tree, determine whether it is a valid binary search tree.

A binary search tree has the following characteristics:

The left subtree of a node contains only numbers less than the current node.
The right subtree of a node contains only numbers greater than the current node.
All left and right subtrees must themselves be binary search trees.
Example 1 :

enter:
    2 
   / \
   1    3 
output: true 
Example 2 :

enter:
    5 
   / \
   1    4 
     / \
     3    6 
Output: false 
Explanation: Input is: [ 5 , 1 , 4 , null , null , 3 , 6 ].
     The root node has a value of 5 , but its right child has a value of 4 .

1. Recursion:

Satisfy that the largest node on the left is less than the root node, and the smallest node on the right is greater than the root node.

code show as below:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode * minNodeBST(TreeNode* root){
        if(root == NULL){
            return NULL;
        }
        
        if(root->left){
            return minNodeBST(root->left);
        }else{
            return root;
        }
    }
    
    TreeNode * maxNodeBST(TreeNode* root){
        if(root == NULL){
            return NULL;
        }
        
        if(root->right){
            return maxNodeBST(root->right);
        }else{
            return root;
        }
    }
    
    bool isValidBST(TreeNode* root) {
        if(root == NULL){
            return true;
        }
        
        TreeNode * minRight = minNodeBST(root->right);
        if(minRight && minRight->val <= root->val){
            return false;
        }
        
        TreeNode * maxLeft = maxNodeBST(root->left);
        if(maxLeft && maxLeft->val >= root->val){
            return false;
        }
        
        return isValidBST(root->left)&&isValidBST(root->right);
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325235809&siteId=291194637