Skip to main content
Back to problems
#145
Easy Algorithms

Binary tree postorder traversal

Stack Tree Depth-First Search Binary Tree
77.7% acceptance
Feb 27, 2026
7756
223
Given the root of a binary tree, return the postorder 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 postorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
    let mut result = Vec::new();
    let mut stack = Vec::new();
    let mut last_visited: Option<Rc<RefCell<TreeNode>>> = None;
    let mut current = root;
    
    while current.is_some() || !stack.is_empty() {
      while let Some(node) = current {
        stack.push(node.clone());
        current = node.borrow().left.clone();
      }
      
      if let Some(peek) = stack.last() {
        let peek_ref = peek.borrow();
        if peek_ref.right.is_some() 
          && !last_visited.as_ref().map_or(false, |lv| Rc::ptr_eq(lv, peek_ref.right.as_ref().unwrap())) {
          current = peek_ref.right.clone();
        } else {
          drop(peek_ref);
          let node = stack.pop().unwrap();
          result.push(node.borrow().val);
          last_visited = Some(node);
        }
      }
    }
    
    result
  }
}