Skip to content

Commit db0044d

Browse files
Merge pull request youngyangyang04#1813 from fwqaaq/patch-25
Update 0538.把二叉搜索树转换为累加树.md
2 parents c3d466e + 26f01c3 commit db0044d

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

problems/0538.把二叉搜索树转换为累加树.md

+49
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,55 @@ object Solution {
375375
}
376376
```
377377

378+
## rust
379+
380+
递归:
381+
382+
```rust
383+
impl Solution {
384+
pub fn convert_bst(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
385+
let mut pre = 0;
386+
Self::traversal(&root, &mut pre);
387+
root
388+
}
389+
390+
pub fn traversal(cur: &Option<Rc<RefCell<TreeNode>>>, pre: &mut i32) {
391+
if cur.is_none() {
392+
return;
393+
}
394+
let mut node = cur.as_ref().unwrap().borrow_mut();
395+
Self::traversal(&node.right, pre);
396+
*pre += node.val;
397+
node.val = *pre;
398+
Self::traversal(&node.left, pre);
399+
}
400+
}
401+
```
402+
403+
迭代:
404+
405+
```rust
406+
impl Solution {
407+
pub fn convert_bst(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
408+
let mut cur = root.clone();
409+
let mut stack = vec![];
410+
let mut pre = 0;
411+
while !stack.is_empty() || cur.is_some() {
412+
while let Some(node) = cur {
413+
cur = node.borrow().right.clone();
414+
stack.push(node);
415+
}
416+
if let Some(node) = stack.pop() {
417+
pre += node.borrow().val;
418+
node.borrow_mut().val = pre;
419+
cur = node.borrow().left.clone();
420+
}
421+
}
422+
root
423+
}
424+
}
425+
```
426+
378427

379428
<p align="center">
380429
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
 (0)