File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+
20+ // LC :O(r × s)
21+ // SC :O(r + s)
22+ use std:: cell:: RefCell ;
23+ use std:: rc:: Rc ;
24+ impl Solution {
25+ pub fn is_subtree (
26+ root : Option < Rc < RefCell < TreeNode > > > ,
27+ sub_root : Option < Rc < RefCell < TreeNode > > > ,
28+ ) -> bool {
29+ fn is_same ( a : & Option < Rc < RefCell < TreeNode > > > , b : & Option < Rc < RefCell < TreeNode > > > ) -> bool {
30+ match ( a, b) {
31+ ( None , None ) => true ,
32+ ( Some ( a) , Some ( b) ) => {
33+ let a = a. borrow ( ) ;
34+ let b = b. borrow ( ) ;
35+ a. val == b. val && is_same ( & a. left , & b. left ) && is_same ( & a. right , & b. right )
36+ }
37+ _ => false ,
38+ }
39+ }
40+
41+ match & root {
42+ None => sub_root. is_none ( ) ,
43+ Some ( node) => {
44+ if is_same ( & root, & sub_root) {
45+ return true ;
46+ }
47+ let node = node. borrow ( ) ;
48+ Self :: is_subtree ( node. left . clone ( ) , sub_root. clone ( ) )
49+ || Self :: is_subtree ( node. right . clone ( ) , sub_root. clone ( ) )
50+ }
51+ }
52+ }
53+ }
You can’t perform that action at this time.
0 commit comments