Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

98. 验证二叉搜索树 #75

Open
Labels
@Geekhyt

Description

@Geekhyt

原题链接

中序遍历

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

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

递归

constisValidBST=function(root){letprev=-Infinityletresult=truefunctioninorder(root){if(root===null)returninorder(root.left)if(root.val<=prev){result=falsereturn}prev=root.valinorder(root.right)}inorder(root)returnresult}
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

迭代

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

constisValidBST=function(root){conststack=[]letprev=-Infinitywhile(root||stack.length){while(root){stack.push(root)root=root.left}root=stack.pop()if(root.val<=prev){returnfalse}prev=root.valroot=root.right}returntrue}
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp