98. Validate Binary Search Tree

problem description

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

Input: [2,1,3]
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

algorithm thought

得到合法的BST,BST有个性质就是中序遍历结果是一个有序数组。所以我们直接中序遍历,每次保存前一个值,如果前一个值大于等于当前遍历的值,那么就不是一个合法的BST,否则就是合法的BST

code

/**
 * 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) {
        stack<TreeNode*> todo;
        long pre=-2147483649;
        while(root||!todo.empty()){
            while(root){
                todo.push(root);
                root=root->left;
            }
            root=todo.top();todo.pop();
            if(root->val<=pre){    
                return false;
            }
            pre=root->val;
            root=root->right;
        }
        return true;
    }
};

algorithm analysis

时间复杂度O(n),遍历的时间,空间复杂度O(n),使用一个栈保存数据。其实可以用之前的Morris tarversal但是LeetCode可能是有bug,代码是正确的但是最后得不到合理的结果。

Last updated