-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7e62199
commit 626122f
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,3 +6,5 @@ pub mod lc143; | |
pub mod lc206; | ||
pub mod lc22; | ||
pub mod lc739; | ||
|
||
pub mod lc572; |