|
| 1 | +use crate::TreeNode; |
| 2 | +use std::cell::RefCell; |
| 3 | +use std::rc::Rc; |
| 4 | +pub struct Solution {} |
| 5 | +impl Solution { |
| 6 | + pub fn is_subtree( |
| 7 | + root: Option<Rc<RefCell<TreeNode>>>, |
| 8 | + sub_root: Option<Rc<RefCell<TreeNode>>>, |
| 9 | + ) -> bool { |
| 10 | + if sub_root.is_none() { |
| 11 | + return true; |
| 12 | + } |
| 13 | + if root.is_none() { |
| 14 | + return false; |
| 15 | + } |
| 16 | + if Self::is_same_tree(root.clone(), sub_root) { |
| 17 | + return true; |
| 18 | + } |
| 19 | + |
| 20 | + let node = root.unwrap().borrow(); |
| 21 | + Self::is_subtree(node.right.clone(), sub_root.clone()) |
| 22 | + || Self::is_subtree(node.left.clone(), sub_root.clone()) |
| 23 | + } |
| 24 | + |
| 25 | + pub fn is_same_tree( |
| 26 | + p: Option<Rc<RefCell<TreeNode>>>, |
| 27 | + q: Option<Rc<RefCell<TreeNode>>>, |
| 28 | + ) -> bool { |
| 29 | + if p.is_none() && q.is_none() { |
| 30 | + return true; |
| 31 | + } |
| 32 | + |
| 33 | + if let (Some(n1), Some(n2)) = (p, q) { |
| 34 | + let node1 = n1.borrow(); |
| 35 | + let node2 = n2.borrow(); |
| 36 | + |
| 37 | + if node1.val != node2.val { |
| 38 | + return false; |
| 39 | + } |
| 40 | + return Self::is_same_tree(node1.left.clone(), node2.left.clone()) |
| 41 | + && Self::is_same_tree(node1.right.clone(), node2.left.clone()); |
| 42 | + } |
| 43 | + false |
| 44 | + } |
| 45 | +} |
0 commit comments