LeetCode 98. Validate Binary Search Tree

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

Example 1:

    2
   / \
  1   3

Binary tree [2,1,3], return true.

Example 2:

    1
   / \
  2   3

Binary tree [1,2,3], return false.

 

 

1,失败解

内存冲突

int GetLength(struct TreeNode* root,int length)
{
    if(root)
    {
        length++;
        if(root -> left){GetLength(root -> left,length);}
        if(root -> right){GetLength(root -> right,length);}
    }
    return length;
}
void inorder(struct TreeNode* root,int *p)
{
    if(root)
    {
        if(root -> left){inorder(root -> left,p);}
        *p = root -> val;
        p++;
        if(root -> right){inorder(root -> right,p);}
    }
}
bool isValidBST(struct TreeNode* root) {
    if(!root){return true;}
    int length = GetLength(root,0);
    int *p = (int*)malloc(length * 2 * sizeof(int));
    int *q;
    q = p;
    inorder(root,p); 
    for(int i = 0;i < length;i++)
    {
        if(*q >= *(q + 1)){return false;}
    }
    return true;
    
}

 

2,正确解

学会使用vector,很方便。不会面对内存问题。

class Solution {
public:
    void inorder(TreeNode* root,vector<int> &v)
    {
        if(root)
        {
            if(root -> left)
                inorder(root -> left,v);
            v.push_back(root -> val);
            if(root -> right)
                inorder(root -> right,v);
        }
    }
    bool isValidBST(TreeNode* root) {
        if(!root)
            return true;
        vector<int> v;
        inorder(root,v);
        for(int i = 0;i < v.size() - 1;i++)
        {
            if(v[i] >= v[i + 1])
                return false;
        }
        return true;
    }
};

 3,测试程序

int _tmain(int argc, _TCHAR* argv[])
{
    struct TreeNode* a = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    struct TreeNode* b = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    bool flag;
    a -> left = b;
    a -> right = NULL;
    a -> val = 0;
    a -> left -> val = -1;
    b -> left = NULL;
    b -> right = NULL;
        
    if(a -> val <= a -> left -> val)
    {
        b = b;
    }
    flag = isValidBST(a);
    printf("\n");


    getchar();
    return 0;
}

 

posted on 2018-03-13 21:39  米兰达莫西  阅读(87)  评论(0编辑  收藏  举报