-
Notifications
You must be signed in to change notification settings - Fork 0
/
symmetric-tree.rs
executable file
·70 lines (57 loc) · 1.78 KB
/
symmetric-tree.rs
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
use std::cell::RefCell;
use std::rc::Rc;
const DUMMY_VALUE: i32 = -1000000;
#[derive(PartialEq, Copy, Clone)]
pub enum Order {
In,
Pre,
Post,
}
impl TreeNode {
pub fn traversal(&self, order: Order, invert: bool) -> Vec<i32> {
fn dfs(node: &TreeNode, ret: &mut Vec<i32>, order: Order, invert: bool) {
if order == Order::Pre {
ret.push(node.val);
}
if let Some(n) = if invert { &node.right } else { &node.left } {
dfs(&n.borrow(), ret, order, invert);
} else {
ret.push(DUMMY_VALUE);
}
if order == Order::In {
ret.push(node.val);
}
if let Some(n) = if invert { &node.left } else { &node.right } {
dfs(&n.borrow(), ret, order, invert);
} else {
ret.push(DUMMY_VALUE);
}
if order == Order::Post {
ret.push(node.val);
}
}
let mut ret = vec![];
dfs(self, &mut ret, order, invert);
ret
}
}
fn tree_eq(root1: &Option<Rc<RefCell<TreeNode>>>, root2: &Option<Rc<RefCell<TreeNode>>>) -> bool {
let default1 = Rc::new(RefCell::new(TreeNode::new(DUMMY_VALUE)));
let default2 = Rc::new(RefCell::new(TreeNode::new(DUMMY_VALUE)));
let n1 = root1.as_ref().unwrap_or(&default1).borrow();
let n2 = root2.as_ref().unwrap_or(&default2).borrow();
n1.traversal(Order::Pre, false) == n2.traversal(Order::Pre, true)
&& n1.traversal(Order::In, false) == n2.traversal(Order::In, true)
&& n1.traversal(Order::Post, false) == n2.traversal(Order::Post, true)
}
impl Solution {
pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
match root {
None => true,
Some(node) => {
let n = node.borrow();
tree_eq(&n.left, &n.right)
}
}
}
}