【leetcode】 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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / 
 2   3
    /
   4
    
     5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

解体思路:中序遍历BST得到的递增的数组,可以使用栈中序遍历得到数组,比较数组元素来判断是否是BST。

class Solution {
public:
    bool isValidBST(TreeNode *root) {
        vector<TreeNode*> stack;
        TreeNode* node = root;
        vector<int> v;
        while (stack.size()>0 || node!=NULL) {//inorder
            if (node!=NULL){
                stack.push_back(node);
                node = node->left;
            }else{
                node = stack.back();
                stack.pop_back();
                v.push_back(node->val);
                node = node->right;
            }
        }

        for(int i=0; v.size()>0 && i<v.size()-1; i++)
            if (v[i] >= v[i+1]) 
                return false;

        return true;
    }
};

疑惑:以下代码采用递归,但是有测试用例通不过,没找到原因。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode *root) {
        return isValidBST(root, INT_MIN, INT_MAX);
    }

    bool isValidBST(TreeNode *root, int lower, int upper){
        if(root == nullptr)
            return true;
        return root->val >= lower && root->val <= upper && isValidBST(root->left, lower, root->val)
            && isValidBST(root->right, root->val, upper);
    }
};
67 / 74 test cases passed.
Status: 

Wrong Answer

 
Submitted: 3 hours, 26 minutes ago
Input: {2147483647}
Output: false
Expected: true
原文地址:https://www.cnblogs.com/zxy1992/p/4386881.html