Skip to main content
Back to problems
#606
Medium Algorithms

Construct string from binary tree

String Tree Depth-First Search Binary Tree
70.6% acceptance
Feb 20, 2026
196
72
Given the root node of a binary tree, create a string representation using preorder traversal with parentheses for children. Omit empty parentheses except when a node has a right child but no left child.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn tree2str(root: Option<Rc<RefCell<TreeNode>>>) -> String {
    fn dfs(node: &Option<Rc<RefCell<TreeNode>>>) -> String {
      match node {
        None => String::new(),
        Some(n) => {
          let n = n.borrow();
          let val = n.val.to_string();
          let left = &n.left;
          let right = &n.right;
          if left.is_none() && right.is_none() {
            return val;
          }
          if right.is_none() {
            return format!("{}({})", val, dfs(left));
          }
          format!("{}({})({})", val, dfs(left), dfs(right))
        }
      }
    }
    dfs(&root)
  }
}