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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use std::rc::Rc;
use std::cell::RefCell;
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
#[macro_export]
macro_rules! btree {
() => {
None
};
($($e:expr), *) => {
{
use std::rc::Rc;
use std::cell::RefCell;
let elems = vec![$(stringify!($e)), *];
let elems = elems.iter().map(|n| n.parse::<i32>().ok()).collect::<Vec<_>>();
let head = Some(Rc::new(RefCell::new($crate::TreeNode::new(elems[0].unwrap()))));
let mut nodes = std::collections::VecDeque::new();
nodes.push_back(head.as_ref().unwrap().clone());
for i in elems[1..].chunks(2) {
let node = nodes.pop_front().unwrap();
if let Some(val) = i[0]{
node.borrow_mut().left = Some(Rc::new(RefCell::new($crate::TreeNode::new(val))));
nodes.push_back(node.borrow().left.as_ref().unwrap().clone());
}
if i.len() > 1 {
if let Some(val) = i[1] {
node.borrow_mut().right = Some(Rc::new(RefCell::new($crate::TreeNode::new(val))));
nodes.push_back(node.borrow().right.as_ref().unwrap().clone());
}
}
}
head
}
};
}
#[cfg(test)]
mod tests {
#[test]
fn test() {
let btree = btree![-1, 2, 3, null];
println!("{:#?}", btree);
}
}