From 56272922060f1ccff4196269dff1091e5315f2ad Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 16 Mar 2022 22:05:03 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880538.=E6=8A=8A?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E4=B8=BA=E7=B4=AF=E5=8A=A0=E6=A0=91.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...38.把二叉搜索树转换为累加树.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 1b07b803..37eb7d0f 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -312,5 +312,47 @@ struct TreeNode* convertBST(struct TreeNode* root){ } ``` +## TypeScript + +> 递归法 + +```typescript +function convertBST(root: TreeNode | null): TreeNode | null { + let pre: number = 0; + function recur(root: TreeNode | null): void { + if (root === null) return; + recur(root.right); + root.val += pre; + pre = root.val; + recur(root.left); + } + recur(root); + return root; +}; +``` + +> 迭代法 + +```typescript +function convertBST(root: TreeNode | null): TreeNode | null { + const helperStack: TreeNode[] = []; + let curNode: TreeNode | null = root; + let pre: number = 0; + while (curNode !== null || helperStack.length > 0) { + while (curNode !== null) { + helperStack.push(curNode); + curNode = curNode.right; + } + curNode = helperStack.pop()!; + curNode.val += pre; + pre = curNode.val; + curNode = curNode.left; + } + return root; +}; +``` + + + -----------------------
From 1856401654174c3b50185471b9bc2888c04237c0 Mon Sep 17 00:00:00 2001 From: Speed <48878102+speedzjy@users.noreply.github.com> Date: Wed, 16 Mar 2022 22:26:46 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200134.=E5=8A=A0?= =?UTF-8?q?=E6=B2=B9=E7=AB=99.md=EF=BC=8C=20=E5=B0=86=E6=9A=B4=E5=8A=9B?= =?UTF-8?q?=E8=A7=A3=E6=B3=95=E4=BB=A3=E7=A0=81=E5=9D=97=E5=90=8E=E7=9A=84?= =?UTF-8?q?=E7=A9=BA=E9=97=B4=E5=A4=8D=E6=9D=82=E5=BA=A6=E8=AF=B4=E6=98=8E?= =?UTF-8?q?=E7=94=B1O(n)=E6=94=B9=E4=B8=BAO(1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0134.加油站.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index ca95af67..1062a91c 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -78,7 +78,7 @@ public: ``` * 时间复杂度:$O(n^2)$ -* 空间复杂度:$O(n)$ +* 空间复杂度:$O(1)$ C++暴力解法在leetcode上提交也可以过。