From 551506b76a22aa343a4116802db41224de000126 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 14 Mar 2022 18:58:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880669.=E4=BF=AE?= =?UTF-8?q?=E5=89=AA=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0669.修剪二叉搜索树.md | 50 ++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 15f6a040..385b2268 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -405,6 +405,56 @@ var trimBST = function (root,low,high) { } ``` +## TypeScript + +> 递归法 + +```typescript +function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null { + if (root === null) return null; + if (root.val < low) { + return trimBST(root.right, low, high); + } + if (root.val > high) { + return trimBST(root.left, low, high); + } + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + return root; +}; +``` + +> 迭代法 + +```typescript +function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null { + while (root !== null && (root.val < low || root.val > high)) { + if (root.val < low) { + root = root.right; + } else if (root.val > high) { + root = root.left; + } + } + let curNode: TreeNode | null = root; + while (curNode !== null) { + while (curNode.left !== null && curNode.left.val < low) { + curNode.left = curNode.left.right; + } + curNode = curNode.left; + } + curNode = root; + while (curNode !== null) { + while (curNode.right !== null && curNode.right.val > high) { + curNode.right = curNode.right.left; + } + curNode = curNode.right; + } + return root; +}; +``` + + + -----------------------