-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsymmetric-tree.rs
69 lines (64 loc) · 2.04 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
// 101. Symmetric Tree
// 🟢 Easy
//
// https://leetcode.com/problems/symmetric-tree/
//
// Tags: Tree - Depth-First Search - Breadth-First Search - Binary Tree
use std::cell::RefCell;
use std::rc::Rc;
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
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,
}
}
}
struct Solution;
impl Solution {
// If the tree is symmetrical, we can recursively explore both left and
// right sub trees comparing the symmetrical values of one to the other,
// if at any point they differ, the tree is not symmetrical.
//
// Time complexity: O(n) - We visit each node once.
// Space complexity: O(n) - Up to one call per node in the call stack.
//
// Runtime 0 ms Beats 100%
// Memory 2.2 MB Beats 64.42%
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,
}
}
}
// Tests.
fn main() {
// let tests = [];
// for test in tests {
// unimplemented!();
// }
println!("No tests for this file!")
}