use std::clone::Clone;
#[derive(Debug, Clone)]
struct Tree<T> {
value : T,
childs : Vec<Tree<T>>,
}
fn to_list<T>(r : &Tree<T>) -> Vec<&T> {
let mut stack = Vec::new();
let mut list = Vec::new();
list.push(&r.value);
stack.push(r.childs.iter());
while let Some(iter) = stack.last_mut() {
if let Some(node) = iter.next() {
list.push(&node.value);
stack.push(node.childs.iter());
} else {
stack.pop();
}
}
list
}
fn map_tree<T, F>(f : F, t: &Tree<T>) -> Tree<T> where
T : Clone,
F : Fn(&T) -> T {
let mut nt = (*t).clone(); // is not equal to `t.to_owned()`
let mut stack = Vec::new();
nt.value = f(&nt.value);
stack.push(nt.childs.iter_mut());
while let Some(iter) = stack.last_mut() {
if let Some(node) = iter.next() {
node.value = f(&node.value);
stack.push(node.childs.iter_mut());
} else {
stack.pop();
}
}
nt
}
fn main() {
let t1 = Tree{
value : 1,
childs : vec![
Tree{
value : 2,
childs : vec![
Tree{
value : 3,
childs : vec![
Tree{
value : 4,
childs : vec![],
},
Tree{
value : 5,
childs : vec![],
},
],
},
Tree{
value : 6,
childs : vec![],
},
],
},
Tree{
value : 7,
childs : vec![
Tree{
value : 8,
childs : vec![],
},
Tree{
value : 9,
childs : vec![],
},
],
},
Tree{
value : 10,
childs : vec![
Tree{
value : 11,
childs : vec![
Tree{
value : 12,
childs : vec![],
},
],
},
Tree{
value : 13,
childs : vec![
Tree{
value : 14,
childs : vec![],
},
],
},
Tree{
value : 15,
childs : vec![],
},
],
},
],
};
println!("{:?}", to_list(&t1));
println!("{:#?}", map_tree(|x| x*10, &t1));
}
출력
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Tree {
value: 10,
childs: [
Tree {
value: 20,
childs: [
Tree {
value: 30,
childs: [
Tree {
value: 40,
childs: [],
},
Tree {
value: 50,
childs: [],
},
],
},
Tree {
value: 60,
childs: [],
},
],
},
Tree {
value: 70,
childs: [
Tree {
value: 80,
childs: [],
},
Tree {
value: 90,
childs: [],
},
],
},
Tree {
value: 100,
childs: [
Tree {
value: 110,
childs: [
Tree {
value: 120,
childs: [],
},
],
},
Tree {
value: 130,
childs: [
Tree {
value: 140,
childs: [],
},
],
},
Tree {
value: 150,
childs: [],
},
],
},
],
}
실행해보기
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=99b9ca3276e1fccc95b13b2a1226c8ce
이제 줘