Skip to content

Commit a32c876

Browse files
authored
Merge pull request neetcode-gh#2664 from rmrt1n/572
Create 0572-subtree-of-another-tree.rs
2 parents ae3f8ec + d155542 commit a32c876

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
use std::rc::Rc;
2+
use std::cell::RefCell;
3+
impl Solution {
4+
pub fn is_subtree(
5+
root: Option<Rc<RefCell<TreeNode>>>,
6+
sub_root: Option<Rc<RefCell<TreeNode>>>
7+
) -> bool {
8+
fn is_sametree(a: Option<Rc<RefCell<TreeNode>>>, b: Option<Rc<RefCell<TreeNode>>>) -> bool {
9+
match (a, b) {
10+
(None, None) => true,
11+
(Some(a), Some(b)) => {
12+
a.borrow().val == b.borrow().val
13+
&& is_sametree(a.borrow().left.clone(), b.borrow().left.clone())
14+
&& is_sametree(a.borrow().right.clone(), b.borrow().right.clone())
15+
}
16+
_ => false,
17+
}
18+
}
19+
20+
match (root, sub_root) {
21+
(_, None) => true,
22+
(None, _) => false,
23+
(Some(root), Some(sub_root)) => {
24+
if is_sametree(Some(root.clone()), Some(sub_root.clone())) {
25+
return true;
26+
}
27+
Solution::is_subtree(root.borrow().left.clone(), Some(sub_root.clone()))
28+
|| Solution::is_subtree(root.borrow().right.clone(), Some(sub_root))
29+
}
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)