Skip to content

Commit 7d7cc16

Browse files
committed
src/bin/binary-tree-paths.rs
1 parent 80a2612 commit 7d7cc16

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

src/bin/binary-tree-paths.rs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
fn main() {}
2+
3+
struct Solution;
4+
5+
// Definition for a binary tree node.
6+
#[derive(Debug, PartialEq, Eq)]
7+
pub struct TreeNode {
8+
pub val: i32,
9+
pub left: Option<Rc<RefCell<TreeNode>>>,
10+
pub right: Option<Rc<RefCell<TreeNode>>>,
11+
}
12+
13+
impl TreeNode {
14+
#[inline]
15+
pub fn new(val: i32) -> Self {
16+
TreeNode {
17+
val,
18+
left: None,
19+
right: None,
20+
}
21+
}
22+
}
23+
24+
use std::rc::Rc;
25+
use std::cell::RefCell;
26+
27+
impl Solution {
28+
pub fn binary_tree_paths(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<String> {
29+
let s = Self::f(root);
30+
s.into_iter().map(|x| x.into_iter().map(|y| y.to_string()).collect::<Vec<String>>().join("->")).collect()
31+
}
32+
33+
fn f(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
34+
if root.is_none() {
35+
return vec![];
36+
}
37+
38+
let left = root.as_ref().unwrap().borrow_mut().left.take();
39+
let right = root.as_ref().unwrap().borrow_mut().right.take();
40+
let v = root.as_ref().unwrap().borrow().val;
41+
match (left, right) {
42+
(Some(x), Some(y)) => {
43+
let f = Self::f(Some(x));
44+
let r = Self::f(Some(y));
45+
f.into_iter().chain(r.into_iter()).map(|mut x| {
46+
x.insert(0, v);
47+
x
48+
}).collect::<Vec<Vec<i32>>>()
49+
}
50+
(Some(x), None) => {
51+
let f = Self::f(Some(x));
52+
f.into_iter().map(|mut x| {
53+
x.insert(0, v);
54+
x
55+
}).collect::<Vec<Vec<i32>>>()
56+
}
57+
(None, Some(y)) => {
58+
let f = Self::f(Some(y));
59+
f.into_iter().map(|mut x| {
60+
x.insert(0, v);
61+
x
62+
}).collect::<Vec<Vec<i32>>>()
63+
}
64+
(None, None) => vec![vec![v]]
65+
}
66+
}
67+
}

0 commit comments

Comments
 (0)