From 6943358d8f75b4c189bcedaa5b79d5c0b0a93c2a Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Fri, 31 Mar 2023 21:58:27 -0400 Subject: [PATCH] =?UTF-8?q?Update=200538.=E6=8A=8A=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E8=BD=AC=E6=8D=A2=E4=B8=BA=E7=B4=AF?= =?UTF-8?q?=E5=8A=A0=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加 python 迭代法 --- ...38.把二叉搜索树转换为累加树.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 29b21840..ad5310e1 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -234,6 +234,26 @@ class Solution: return root ``` +**迭代** +```python +class Solution: + def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if not root: return root + stack = [] + result = [] + cur = root + pre = 0 + while cur or stack: + if cur: + stack.append(cur) + cur = cur.right + else: + cur = stack.pop() + cur.val+= pre + pre = cur.val + cur =cur.left + return root +``` ## Go