From 54144f3a6b59bb8be22111a489d60edc49eeffa9 Mon Sep 17 00:00:00 2001 From: Relsola Date: Fri, 27 Oct 2023 19:49:03 +0800 Subject: [PATCH] =?UTF-8?q?Update=2098.=E9=AA=8C=E8=AF=81=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md=20=E5=A2=9E=E5=8A=A0js?= =?UTF-8?q?=E5=92=8Cts=E8=BF=AD=E4=BB=A3=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0098.验证二叉搜索树.md | 61 ++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 0a64266e..184060a5 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -595,6 +595,43 @@ var isValidBST = function (root) { }; ``` +> 迭代法: + +```JavaScript +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +let pre = null; +var isValidBST = function (root) { + const queue = []; + let cur = root; + let pre = null; + while (cur !== null || queue.length !== 0) { + if (cur !== null) { + queue.push(cur); + cur = cur.left; + } else { + cur = queue.pop(); + if (pre !== null && cur.val <= pre.val) { + return false; + } + pre = cur; + cur = cur.right; + } + } + return true; +}; +``` + ### TypeScript > 辅助数组解决: @@ -637,6 +674,30 @@ function isValidBST(root: TreeNode | null): boolean { }; ``` +> 迭代法: + +```TypeScript +function isValidBST(root: TreeNode | null): boolean { + const queue: TreeNode[] = []; + let cur: TreeNode | null = root; + let pre: TreeNode | null = null; + while (cur !== null || queue.length !== 0) { + if (cur !== null) { + queue.push(cur); + cur = cur.left; + } else { + cur = queue.pop()!; + if (pre !== null && cur!.val <= pre.val) { + return false; + } + pre = cur; + cur = cur!.right; + } + } + return true; +} +``` + ### Scala 辅助数组解决: