Skip to content

Commit

Permalink
Solve leetcode 572
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielseibel1 committed Oct 7, 2023
1 parent 7e62199 commit 626122f
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
55 changes: 55 additions & 0 deletions src/lc572.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use std::rc::Rc;
use std::cell::RefCell;
use std::path::Iter;

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,
}
}
}

struct Solution {}

impl Solution {
pub fn is_subtree(root: Tree, sub_root: Tree) -> bool {
dfs_fits(&root, &sub_root)
}
}

fn same(t1: &Tree, t2: &Tree) -> bool {
if t2.is_none() || t1.is_none() {
return t1 == t2;
}
let t1 = t1.as_ref().unwrap().borrow();
let t2 = t2.as_ref().unwrap().borrow();
return t1.val == t2.val &&
same(&t1.left, &t2.left) &&
same(&t1.right, &t2.right);
}

fn dfs_fits(tree: &Tree, shape: &Tree) -> bool {
match &tree {
None => shape.is_none(),
Some(t) => {
if same(&tree, &shape) {
return true;
}
dfs_fits(&t.borrow().left, &shape) ||
dfs_fits(&t.borrow().right, &shape)
}
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ pub mod lc143;
pub mod lc206;
pub mod lc22;
pub mod lc739;

pub mod lc572;

0 comments on commit 626122f

Please sign in to comment.