From 26f01c3ef9db64c890ae077c16a50544b990701f Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+fwqaaq@users.noreply.github.com> Date: Fri, 9 Dec 2022 20:15:28 +0800 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 --- ...38.把二叉搜索树转换为累加树.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 36dbfa70..2f759d39 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -396,6 +396,30 @@ impl Solution { } ``` +迭代: + +```rust +impl Solution { + pub fn convert_bst(root: Option>>) -> Option>> { + let mut cur = root.clone(); + let mut stack = vec![]; + let mut pre = 0; + while !stack.is_empty() || cur.is_some() { + while let Some(node) = cur { + cur = node.borrow().right.clone(); + stack.push(node); + } + if let Some(node) = stack.pop() { + pre += node.borrow().val; + node.borrow_mut().val = pre; + cur = node.borrow().left.clone(); + } + } + root + } +} +``` +