diff --git "a/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" "b/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" index dc576c60bb..9bf7405d06 100644 --- "a/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" +++ "b/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.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(); //回溯 + } + } +} +``` +