Skip to main content
Back to problems
#226
Easy Algorithms

Invert binary tree

Tree Depth-First Search Breadth-First Search Binary Tree
79.9% acceptance
Feb 27, 2026
15151
252
Given the root of a binary tree, invert the tree, and return its root.

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 invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
    if let Some(node) = root {
      let mut node_ref = node.borrow_mut();
      let left = node_ref.left.take();
      let right = node_ref.right.take();
      node_ref.left = Self::invert_tree(right);
      node_ref.right = Self::invert_tree(left);
      drop(node_ref);
      Some(node)
    } else {
      None
    }
  }
}