• [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.

    解法一:曾经用pre_value = INT_MIN记录最小值,然后不断判断当前节点是否大于pre_value来判断。原来行,后来就不行了。INT_MIN似乎有bug(https://leetcode.com/discuss/14886/order-traversal-please-rely-buggy-int_max-int_min-solutions)。现在改用pre记录前一个节点来判断。

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

    解法二:递归的方法。时间复杂度O(n),空间复杂度O(logN)

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool isValidBST(TreeNode *root) {
    13         return isValidBST(root, LONG_MIN, LONG_MAX);
    14     }
    15     bool isValidBST(TreeNode *root, long lower_value, long upper_value) {
    16         if (root == NULL) return true;
    17         
    18         return root->val > lower_value && root->val < upper_value
    19                && isValidBST(root->left, lower_value, root->val)
    20                && isValidBST(root->right, root->val, upper_value);
    21     }
    22 };
  • 相关阅读:
    org.apache.jasper.JasperException
    泛型接口
    Mysql学习
    深入分析ClassLoader
    空格哥的第一篇Blog
    [Maven] Missing artifact
    sftp新建用户步骤
    遍历map的6种方式
    利用aop插入异常日志的2种方式
    Mybatis-Oralce批量插入方法
  • 原文地址:https://www.cnblogs.com/vincently/p/4235672.html
Copyright © 2020-2023  润新知