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.

S1: recursion O(n)

一层层更新当前的min max boundary

class Solution {
public:
    bool isValidBST(TreeNode* root) {
        return bfs(root, LONG_MIN, LONG_MAX);
    }

    bool bfs(TreeNode* node, long preMin, long preMax) {
        if (!node) {
            return true;
        }
        if (node->val <= preMin || node->val >= preMax) {
            return false;
        }
        return bfs(node->left, preMin, node->val) && bfs(node->right, node->val, preMax);
    }
};

S2: inorder traversal O(n)

inorder traversal是排好序的

    bool isValidBST(TreeNode* root) {
        stack<TreeNode*> stk;
        TreeNode* node = root;
        long pre = LONG_MIN;
        while (node || !stk.empty()) {
            while(node) {
                stk.push(node);
                node = node->left;
            }
            node = stk.top();
            if (pre >= node->val) {
                return false;
            }
            pre = node->val;
            stk.pop();
            node = node->right;
        }
        return true;
    }

results matching ""

    No results matching ""