NO.98 verify binary search tree

Given a binary tree to determine if it is a valid binary search tree.

Suppose a binary search tree having the following characteristics:

    Left child node of the tree contains only less than the current node number.
    Right subtree contain only greater than the number of nodes of the current node.
    All left subtree and right subtree itself must also be binary search tree.

Example 1:

Input:
    2
   / \
  1 3
Output: true

Example 2:

Input:
    5
   / \
  14
     / \
    36
Output: false
interpretation: Input as: [5,1,4, null, null, 3,6].
     5 is a root node, but it is the right child node 4.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
static void DFS(struct TreeNode* root,bool  *ret,int min,int max,unsigned char flag)
{
    if(!(*ret)||!root)return;
    if(flag==1)
    {//左子树
        if(root->val>=max)*ret=false;
        DFS(root->left,ret,0,root->val,1);
        DFS(root->right,ret,root->val,max,0);
    }
    else if(flag==2)
    {//右子树
        if(root->val<=min)*ret=false;
        DFS(root->left,ret,min,root->val,0);
        DFS(root->right,ret,root->val,0,2);
    }
    else
    {
        if(root->val>=max||root->val<=min)*ret=false;
        DFS(root->left,ret,min,root->val,0);
        DFS(root->right,ret,root->val,max,0);
    }
}

bool isValidBST(struct TreeNode* root){
    if(!root)return true;
    bool ret=true;
    DFS(root->left,&ret,0,root->val,1);
    DFS(root->right,&ret,root->val,0,2);
    //printf("%d \n",ret);
    return ret;
}

When execution: 24 ms, beat the 69.71% of users Validate Binary Search Tree in C submission

Memory consumption: 10 MB, defeated 100.00% of user Validate Binary Search Tree in C submission

Guess you like

Origin blog.csdn.net/xuyuanwang19931014/article/details/91378400