LeetCode 98 -- verify binary search tree

Keywords: C++ less

1. topic

2. answers

For a node, there are four situations:

  • The node is empty or both left and right nodes of the node are empty;
  • Only the right node is empty;
  • Only the left node is empty;
  • Left and right nodes are not empty;

If the left and right sub nodes of the current node satisfy the condition of binary search tree, we can recursively judge whether the left and right sub trees are binary search trees. If the left and right subtrees also meet the binary search tree condition, and the maximum node (i.e. the predecessor node) value of the left subtree is less than the current node value, and the minimum node (i.e. the successor node) value of the right subtree is greater than the current node value, then the whole tree is a binary search tree.

/**
 * 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:
    bool isValidBST(TreeNode* root) {
        
        if (root == NULL || (root->left == NULL && root->right == NULL)) return true;
        else if (root->left != NULL && root->right == NULL)
        {
            if (root->left->val >= root->val) return false;
            else return isValidBST(root->left) && isValidprev_node(root->left, root->val);
        }
        else if (root->left == NULL && root->right != NULL)
        {
            if (root->right->val <= root->val) return false;
            else return isValidBST(root->right) && isValidnext_node(root->right, root->val);
        }
        else 
        {
            if (root->right->val <= root->val || root->left->val >= root->val) return false;
            else return isValidBST(root->left) && isValidprev_node(root->left, root->val) 
                && isValidBST(root->right) && isValidnext_node(root->right, root->val);
        }        
    }
    
    // Whether the precursor node is valid
    bool isValidprev_node(TreeNode* root, int data)
    {
        while (root->right != NULL)
        {
            root = root->right;
        }
        if (root->val < data) return true;
        else return false;
    }
    // Whether the successor node is valid
    bool isValidnext_node(TreeNode* root, int data)
    {
        while (root->left != NULL)
        {
            root = root->left;
        }
        if (root->val > data) return true;
        else return false;
    }
      
};

For more highlights, please pay attention to "seniusen"!

Posted by jpearson on Wed, 04 Dec 2019 17:51:31 -0800