Skip to content

Commit 82cfccf

Browse files
authored
subtree of another tree solution
1 parent 2288072 commit 82cfccf

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
use std::rc::Rc;
20+
use std::cell::RefCell;
21+
impl Solution {
22+
pub fn is_subtree(root: Option<Rc<RefCell<TreeNode>>>, sub_root: Option<Rc<RefCell<TreeNode>>>) -> bool {
23+
match &root {
24+
Some(u) => {
25+
let u = u.borrow();
26+
match &sub_root {
27+
Some(v) => {
28+
let v = v.borrow();
29+
Self::solve(root.clone(), sub_root.clone())
30+
|| Self::is_subtree(u.left.clone(), sub_root.clone())
31+
|| Self::is_subtree(u.right.clone(), sub_root.clone())
32+
},
33+
None => false,
34+
}
35+
},
36+
None => sub_root.is_none(),
37+
}
38+
}
39+
fn solve(root: Option<Rc<RefCell<TreeNode>>>, sub_root: Option<Rc<RefCell<TreeNode>>>) -> bool {
40+
match root {
41+
Some(u) => {
42+
let u = u.borrow();
43+
match &sub_root {
44+
Some(v) => {
45+
let v = v.borrow();
46+
u.val == v.val
47+
&& Self::solve(u.left.clone(), v.left.clone())
48+
&& Self::solve(u.right.clone(), v.right.clone())
49+
},
50+
None => false,
51+
}
52+
},
53+
None => sub_root.is_none(),
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)