Skip to main content
Back to problems
#101
Easy Algorithms

Symmetric tree

Tree Depth-First Search Breadth-First Search Binary Tree
60.8% acceptance
Feb 27, 2026
16756
455
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
// 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_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
    fn is_mirror(left: Option<Rc<RefCell<TreeNode>>>, right: Option<Rc<RefCell<TreeNode>>>) -> bool {
      match (left, right) {
        (None, None) => true,
        (None, Some(_)) | (Some(_), None) => false,
        (Some(l), Some(r)) => {
          let l_borrow = l.borrow();
          let r_borrow = r.borrow();
          l_borrow.val == r_borrow.val
            && is_mirror(l_borrow.left.clone(), r_borrow.right.clone())
            && is_mirror(l_borrow.right.clone(), r_borrow.left.clone())
        }
      }
    }
    
    match root {
      None => true,
      Some(node) => {
        let borrow = node.borrow();
        is_mirror(borrow.left.clone(), borrow.right.clone())
      }
    }
  }
}