From 4bae1e84baffb99c60f073eeca515c9c4a14697b Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 19 Nov 2022 01:39:14 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91=E4=B8=AD?= =?UTF-8?q?=E9=80=92=E5=BD=92=E5=B8=A6=E7=9D=80=E5=9B=9E=E6=BA=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树中递归带着回溯.md | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/二叉树中递归带着回溯.md b/problems/二叉树中递归带着回溯.md index dc576c60..9bf7405d 100644 --- a/problems/二叉树中递归带着回溯.md +++ b/problems/二叉树中递归带着回溯.md @@ -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>>) -> Vec { + let mut res = vec![]; + let mut path = vec![]; + Self::recur(&root, &mut path, &mut res); + res + } + + pub fn recur( + root: &Option>>, + path: &mut Vec, + res: &mut Vec, + ) { + 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(); //回溯 + } + } +} +``` +