Merge pull request #1762 from Jack-Zhang-1314/patch-20

Update 二叉树中递归带着回溯.md about rust
This commit is contained in:
程序员Carl
2022-12-04 10:42:40 +08:00
committed by GitHub

View File

@ -617,6 +617,75 @@ func _binaryTreePaths3(_ root: TreeNode, res: inout [String], paths: inout [Int]
}
```
### Rust
> 100.相同的树
```rsut
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn is_same_tree(
p: Option<Rc<RefCell<TreeNode>>>,
q: Option<Rc<RefCell<TreeNode>>>,
) -> bool {
match (p, q) {
(None, None) => true,
(None, Some(_)) => false,
(Some(_), None) => false,
(Some(n1), Some(n2)) => {
if n1.borrow().val == n2.borrow().val {
let right =
Self::is_same_tree(n1.borrow().left.clone(), n2.borrow().left.clone());
let left =
Self::is_same_tree(n1.borrow().right.clone(), n2.borrow().right.clone());
right && left
} else {
false
}
}
}
}
}
```
> 257.二叉树的不同路径
```rust
// 递归
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn binary_tree_paths(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<String> {
let mut res = vec![];
let mut path = vec![];
Self::recur(&root, &mut path, &mut res);
res
}
pub fn recur(
root: &Option<Rc<RefCell<TreeNode>>>,
path: &mut Vec<String>,
res: &mut Vec<String>,
) {
let node = root.as_ref().unwrap().borrow();
path.push(node.val.to_string());
if node.left.is_none() && node.right.is_none() {
res.push(path.join("->"));
return;
}
if node.left.is_some() {
Self::recur(&node.left, path, res);
path.pop(); //回溯
}
if node.right.is_some() {
Self::recur(&node.right, path, res);
path.pop(); //回溯
}
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">