1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
| impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
impl Tree {
fn get_val(&self) -> i32 {
return self.value;
}
fn set_val(&mut self, val: i32) -> i32 {
self.value = val;
return self.value;
}
fn insert(&mut self, dir: &String, val: Tree) {
assert!(dir == "left" || dir == "right");
match dir.as_ref() {
"left" => self.left = Some(Box::new(val)),
"right" => self.right = Some(Box::new(val)),
_ => {
println!("Insert Error: only left and right supported");
process::exit(1);
}
}
}
fn delete(&mut self, dir: &String) {
assert!(dir == "left" || dir == "right");
match dir.as_ref() {
"left" => self.left = None,
"right" => self.right = None,
_ => {
println!("Insert Error: only left and right supported");
process::exit(1);
}
}
}
}
// 非消耗性遍历
fn traverse(tree: &Tree) {
println!("Node Value: {:?}", tree.value);
match tree.left {
Some(ref x) => traverse(x),
_ => {}
}
match tree.right {
Some(ref x) => traverse(x),
_ => {}
}
}
|