mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 二叉树中递归带着回溯.md
This commit is contained in:
@ -649,6 +649,43 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> 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">
|
<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