From 4341179d9381c7d1a927ba17bcb2c7dce2371af5 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+fwqaaq@users.noreply.github.com> Date: Fri, 9 Dec 2022 20:02:58 +0800 Subject: [PATCH 1/2] =?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 | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 9940e604..36dbfa70 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -371,6 +371,31 @@ object Solution { } ``` +## rust + +递归: + +```rust +impl Solution { + pub fn convert_bst(root: Option>>) -> Option>> { + let mut pre = 0; + Self::traversal(&root, &mut pre); + root + } + + pub fn traversal(cur: &Option>>, pre: &mut i32) { + if cur.is_none() { + return; + } + let mut node = cur.as_ref().unwrap().borrow_mut(); + Self::traversal(&node.right, pre); + *pre += node.val; + node.val = *pre; + Self::traversal(&node.left, pre); + } +} +``` +

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 2/2] =?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 + } +} +``` +