Skip to content

Commit fa2e731

Browse files
committed
feat: add symmetric tree problem solution
1 parent b2229e8 commit fa2e731

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

src/easy/symmetric_tree.rs

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#![allow(dead_code)]
2+
use std::rc::Rc;
3+
use std::cell::RefCell;
4+
5+
#[derive(Debug, PartialEq, Eq)]
6+
pub struct TreeNode {
7+
pub val: i32,
8+
pub left: Option<Rc<RefCell<TreeNode>>>,
9+
pub right: Option<Rc<RefCell<TreeNode>>>,
10+
}
11+
12+
impl TreeNode {
13+
#[inline]
14+
pub fn new(val: i32) -> Self {
15+
TreeNode {
16+
val,
17+
left: None,
18+
right: None
19+
}
20+
}
21+
}
22+
23+
pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
24+
if root.is_none() {
25+
return true;
26+
}
27+
28+
let mut queue = std::collections::VecDeque::new();
29+
30+
queue.push_back(root.clone());
31+
queue.push_back(root.clone());
32+
33+
while !queue.is_empty() {
34+
let t1 = queue.pop_front().unwrap();
35+
let t2 = queue.pop_front().unwrap();
36+
if t1.is_none() && t2.is_none() {
37+
continue;
38+
}
39+
if t1.is_none() || t2.is_none() {
40+
return false;
41+
}
42+
let t1 = t1.unwrap();
43+
let t2 = t2.unwrap();
44+
let t1 = t1.borrow();
45+
let t2 = t2.borrow();
46+
if t1.val != t2.val {
47+
return false;
48+
}
49+
queue.push_back(t1.left.clone());
50+
queue.push_back(t2.right.clone());
51+
queue.push_back(t1.right.clone());
52+
queue.push_back(t2.left.clone());
53+
}
54+
true
55+
56+
}
57+
58+
59+
#[cfg(test)]
60+
mod tests {
61+
use super::*;
62+
63+
#[test]
64+
fn test_101() {
65+
let mut t1 = TreeNode::new(1);
66+
let mut t2 = TreeNode::new(2);
67+
let mut t3 = TreeNode::new(2);
68+
let t4 = TreeNode::new(3);
69+
let t5 = TreeNode::new(4);
70+
let t6 = TreeNode::new(4);
71+
let t7 = TreeNode::new(3);
72+
t3.left = Some(Rc::new(RefCell::new(t6)));
73+
t3.right = Some(Rc::new(RefCell::new(t7)));
74+
t2.left = Some(Rc::new(RefCell::new(t4)));
75+
t2.right = Some(Rc::new(RefCell::new(t5)));
76+
t1.left = Some(Rc::new(RefCell::new(t2)));
77+
t1.right = Some(Rc::new(RefCell::new(t3)));
78+
assert_eq!(is_symmetric(Some(Rc::new(RefCell::new(t1)))), true);
79+
}
80+
}

0 commit comments

Comments
 (0)