-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathlib.rs
90 lines (88 loc) · 2.36 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* @lc app=leetcode.cn id=572 lang=rust
*
* [572] 另一个树的子树
*/
// #[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
struct Solution {}
// @lc code=start
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn is_subtree(s: Option<Rc<RefCell<TreeNode>>>, t: Option<Rc<RefCell<TreeNode>>>) -> bool {
if t.is_none() {
return true;
}
if s.is_none() {
return false;
}
let s_borrow = s.as_ref().unwrap().borrow();
let s_left = if s_borrow.left.is_some() {
Some(Rc::clone(s_borrow.left.as_ref().unwrap()))
} else {
None
};
let s_right = if s_borrow.right.is_some() {
Some(Rc::clone(s_borrow.right.as_ref().unwrap()))
} else {
None
};
return Self::is_subtree(s_left, Some(Rc::clone(t.as_ref().unwrap())))
|| Self::is_subtree(s_right.clone(), Some(Rc::clone(t.as_ref().unwrap())))
|| Self::dfs(&s, &t);
}
fn dfs(s: &Option<Rc<RefCell<TreeNode>>>, t: &Option<Rc<RefCell<TreeNode>>>) -> bool {
if s.is_none() && t.is_none() {
return true;
}
if s.is_none() || t.is_none() {
return false;
}
let s_borrow = s.as_ref().unwrap().borrow();
let s_val = s_borrow.val;
let s_left = &s_borrow.left;
let s_right = &s_borrow.right;
let t_borrow = t.as_ref().unwrap().borrow();
let t_val = t_borrow.val;
let t_left = &t_borrow.left;
let t_right = &t_borrow.right;
if s_val != t_val {
return false;
}
return Self::dfs(s_left, t_left) && Self::dfs(s_right, t_right);
}
}
// @lc code=end