Skip to main content
Back to problems
#144
Easy Algorithms

Binary tree preorder traversal

Stack Tree Depth-First Search Binary Tree
75.2% acceptance
Feb 27, 2026
8832
234
Given the root of a binary tree, return the preorder traversal of its nodes' values.

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 preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
    let mut result = Vec::new();
    let mut stack = Vec::new();
    
    if let Some(node) = root {
      stack.push(node);
    }
    
    while let Some(node) = stack.pop() {
      let node_ref = node.borrow();
      result.push(node_ref.val);
      
      if let Some(right) = node_ref.right.clone() {
        stack.push(right);
      }
      if let Some(left) = node_ref.left.clone() {
        stack.push(left);
      }
    }
    
    result
  }
}