-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0101-symmetric-tree.rs
24 lines (24 loc) · 983 Bytes
/
0101-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
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
// Time O(n) - Space O(h)
pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
// An internal function that checks two nodes situated in a
// symmetrical position in the tree.
fn dfs(left: Option<Rc<RefCell<TreeNode>>>, right: Option<Rc<RefCell<TreeNode>>>) -> bool {
match (left, right) {
(None, None) => true,
(None, Some(_)) | (Some(_), None) => false,
(Some(left), Some(right)) => {
left.borrow().val == right.borrow().val
&& dfs(left.borrow().left.clone(), right.borrow().right.clone())
&& dfs(left.borrow().right.clone(), right.borrow().left.clone())
}
}
}
match root {
Some(root) => dfs(root.borrow().left.clone(), root.borrow().right.clone()),
None => true,
}
}
}