Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

98. 验证二叉搜索树 #75

Open
Geekhyt opened this issue Sep 19, 2021 · 2 comments
Open

98. 验证二叉搜索树 #75

Geekhyt opened this issue Sep 19, 2021 · 2 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Sep 19, 2021

原题链接

中序遍历

二叉搜索树需要满足以下三个条件:

  • 节点的左子树只包含 小于 当前节点的数。
  • 节点的右子树只包含 大于 当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。
  1. 二叉搜索树在中序遍历时得到的序列一定是升序的
  2. 进行中序遍历,判断当前节点是否大于前一个节点
  3. 如果比前一个大,说明满足,则继续遍历,否则直接返回 false

递归

const isValidBST = function(root) {
    let prev = -Infinity
    let result = true
    function inorder(root) {
        if (root === null) return
        inorder(root.left)
        if (root.val <= prev) {
            result = false
            return 
        }
        prev = root.val
        inorder(root.right)
    }
    inorder(root)
    return result
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

迭代

递归隐式地维护了一个栈,在迭代的时候我们需要显式地将这个栈模拟出来。

const isValidBST = function (root) {
    const stack = []
    let prev = -Infinity
    while (root || stack.length) {
        while (root) {
            stack.push(root)
            root = root.left
        }
        root = stack.pop()
        if (root.val <= prev) {
            return false
        }
        prev = root.val
        root = root.right
    }
    return true
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)
@Geekhyt Geekhyt added the 简单 label Sep 19, 2021
@eavan5
Copy link

eavan5 commented Sep 26, 2021

这个中序递归有问题。。

@Geekhyt
Copy link
Owner Author

Geekhyt commented Sep 30, 2021

这个中序递归有问题。。

已修正

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants