-
Notifications
You must be signed in to change notification settings - Fork 0
/
same_tree.rs
78 lines (67 loc) · 2.72 KB
/
same_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
71
72
73
74
75
76
77
78
#![allow(dead_code)]
use std::cell::RefCell;
use std::rc::Rc;
type Tree = Option<Rc<RefCell<TreeNode>>>;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Tree,
pub right: Tree,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
pub fn is_same_tree(p: Tree, q: Tree) -> bool {
match (p, q) {
(None, None) => true,
(Some(p), Some(q)) => {
p.borrow().val == q.borrow().val
&& is_same_tree(p.borrow().left.clone(), q.borrow().left.clone())
&& is_same_tree(p.borrow().right.clone(), q.borrow().right.clone())
}
_ => false,
}
}
/*
Algorithm - Recursion
- If both trees are empty then they are same
- If both trees are non-empty
- Check if current data of both trees are same
- Recursively check if left subtree of both trees are same
- Recursively check if right subtree of both trees are same
- If one of them is empty and other is not, then they are not same
Complexity
- Time is O(n) where n is the number of nodes in the tree
- Space is O(n) where n is the number of nodes in the tree
*/
#[test]
fn test_is_same_tree() {
let tree1 = Some(Rc::new(RefCell::new(TreeNode::new(1))));
let tree2 = Some(Rc::new(RefCell::new(TreeNode::new(1))));
assert_eq!(is_same_tree(tree1, tree2), true);
let tree1 = Some(Rc::new(RefCell::new(TreeNode::new(1))));
let tree2 = Some(Rc::new(RefCell::new(TreeNode::new(2))));
assert_eq!(is_same_tree(tree1, tree2), false);
let tree1 = Some(Rc::new(RefCell::new(TreeNode::new(1))));
let tree2 = Some(Rc::new(RefCell::new(TreeNode::new(1))));
tree1.as_ref().unwrap().borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(2))));
tree2.as_ref().unwrap().borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(2))));
assert_eq!(is_same_tree(tree1, tree2), false);
let tree1 = Some(Rc::new(RefCell::new(TreeNode::new(1))));
let tree2 = Some(Rc::new(RefCell::new(TreeNode::new(1))));
tree1.as_ref().unwrap().borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(2))));
tree2.as_ref().unwrap().borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(2))));
assert_eq!(is_same_tree(tree1, tree2), true);
let tree1 = Some(Rc::new(RefCell::new(TreeNode::new(1))));
let tree2 = Some(Rc::new(RefCell::new(TreeNode::new(1))));
tree1.as_ref().unwrap().borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(2))));
tree2.as_ref().unwrap().borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(2))));
assert_eq!(is_same_tree(tree1, tree2), false);
}