#572
Easy Algorithms Subtree of another tree
Tree Depth-First Search String Matching Binary Tree Hash Function
51.3% acceptance
Jan 13, 2026
8865
601
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.
Solution
Rust
Time O(n)
Space O(n)
// 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::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn is_subtree(root: Option<Rc<RefCell<TreeNode>>>, sub_root: Option<Rc<RefCell<TreeNode>>>) -> bool {
fn same(a: &Option<Rc<RefCell<TreeNode>>>, b: &Option<Rc<RefCell<TreeNode>>>) -> bool {
match (a, b) {
(None, None) => true,
(Some(x), Some(y)) => {
let x = x.borrow(); let y = y.borrow();
x.val == y.val && same(&x.left, &y.left) && same(&x.right, &y.right)
}
_ => false,
}
}
fn check(root: &Option<Rc<RefCell<TreeNode>>>, sub: &Option<Rc<RefCell<TreeNode>>>) -> bool {
match root {
None => same(root, sub),
Some(n) => {
let n = n.borrow();
same(root, sub) || check(&n.left, sub) || check(&n.right, sub)
}
}
}
check(&root, &sub_root)
}
}