Skip to content

Commit

Permalink
Merge pull request #2664 from rmrt1n/572
Browse files Browse the repository at this point in the history
Create 0572-subtree-of-another-tree.rs
  • Loading branch information
tahsintunan committed Jul 22, 2023
2 parents ae3f8ec + d155542 commit a32c876
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions rust/0572-subtree-of-another-tree.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn is_subtree(
root: Option<Rc<RefCell<TreeNode>>>,
sub_root: Option<Rc<RefCell<TreeNode>>>
) -> bool {
fn is_sametree(a: Option<Rc<RefCell<TreeNode>>>, b: Option<Rc<RefCell<TreeNode>>>) -> bool {
match (a, b) {
(None, None) => true,
(Some(a), Some(b)) => {
a.borrow().val == b.borrow().val
&& is_sametree(a.borrow().left.clone(), b.borrow().left.clone())
&& is_sametree(a.borrow().right.clone(), b.borrow().right.clone())
}
_ => false,
}
}

match (root, sub_root) {
(_, None) => true,
(None, _) => false,
(Some(root), Some(sub_root)) => {
if is_sametree(Some(root.clone()), Some(sub_root.clone())) {
return true;
}
Solution::is_subtree(root.borrow().left.clone(), Some(sub_root.clone()))
|| Solution::is_subtree(root.borrow().right.clone(), Some(sub_root))
}
}
}
}

0 comments on commit a32c876

Please sign in to comment.