Skip to content

Commit f36099f

Browse files
authored
Merge pull request #2340 from DaleSeo/main
[DaleSeo] WEEK 15 solutions
2 parents 27da15e + e51df3a commit f36099f

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

subtree-of-another-tree/DaleSeo.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Definition for a binary tree node.
2+
// #[derive(Debug, PartialEq, Eq)]
3+
// pub struct TreeNode {
4+
// pub val: i32,
5+
// pub left: Option<Rc<RefCell<TreeNode>>>,
6+
// pub right: Option<Rc<RefCell<TreeNode>>>,
7+
// }
8+
//
9+
// impl TreeNode {
10+
// #[inline]
11+
// pub fn new(val: i32) -> Self {
12+
// TreeNode {
13+
// val,
14+
// left: None,
15+
// right: None
16+
// }
17+
// }
18+
// }
19+
20+
// LC :O(r × s)
21+
// SC :O(r + s)
22+
use std::cell::RefCell;
23+
use std::rc::Rc;
24+
impl Solution {
25+
pub fn is_subtree(
26+
root: Option<Rc<RefCell<TreeNode>>>,
27+
sub_root: Option<Rc<RefCell<TreeNode>>>,
28+
) -> bool {
29+
fn is_same(a: &Option<Rc<RefCell<TreeNode>>>, b: &Option<Rc<RefCell<TreeNode>>>) -> bool {
30+
match (a, b) {
31+
(None, None) => true,
32+
(Some(a), Some(b)) => {
33+
let a = a.borrow();
34+
let b = b.borrow();
35+
a.val == b.val && is_same(&a.left, &b.left) && is_same(&a.right, &b.right)
36+
}
37+
_ => false,
38+
}
39+
}
40+
41+
match &root {
42+
None => sub_root.is_none(),
43+
Some(node) => {
44+
if is_same(&root, &sub_root) {
45+
return true;
46+
}
47+
let node = node.borrow();
48+
Self::is_subtree(node.left.clone(), sub_root.clone())
49+
|| Self::is_subtree(node.right.clone(), sub_root.clone())
50+
}
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)