mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #1813 from fwqaaq/patch-25
Update 0538.把二叉搜索树转换为累加树.md
This commit is contained in:
@ -375,6 +375,55 @@ object Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## rust
|
||||||
|
|
||||||
|
递归:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn convert_bst(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
let mut pre = 0;
|
||||||
|
Self::traversal(&root, &mut pre);
|
||||||
|
root
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn traversal(cur: &Option<Rc<RefCell<TreeNode>>>, 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
迭代:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn convert_bst(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
Reference in New Issue
Block a user