Iterative Inorder Walk With Stack

An explicit stack replaces recursion for in-order traversal: push left spine nodes, pop to visit, then continue into the right subtree.

RustData Integrity

Code

rustsnippet
53 lines
use std::cmp::Ordering;

struct Node {
    value: i32,
    left: Option<Box<Node>>,
    right: Option<Box<Node>>,
}

impl Node {
    fn new(value: i32) -> Self {
        Self { value, left: None, right: None }
    }

    fn insert(&mut self, value: i32) {
        match value.cmp(&self.value) {
            Ordering::Less => match self.left {
                Some(ref mut child) => child.insert(value),
                None => self.left = Some(Box::new(Node::new(value))),
            },
            Ordering::Greater => match self.right {
                Some(ref mut child) => child.insert(value),
                None => self.right = Some(Box::new(Node::new(value))),
            },
            Ordering::Equal => {} // 重复值忽略
        }
    }
}

// 迭代 (iterative) 中序遍历:显式栈代替递归,一路向左压栈,弹出访问后转向右子树
fn inorder(root: &Node) -> Vec<i32> {
    let mut out = Vec::new();
    let mut stack: Vec<&Node> = Vec::new();
    let mut current = Some(root);
    while current.is_some() || !stack.is_empty() {
        while let Some(node) = current {
            stack.push(node);
            current = node.left.as_deref();
        }
        if let Some(node) = stack.pop() {
            out.push(node.value);
            current = node.right.as_deref();
        }
    }
    out
}

fn main() {
    let mut root = Node::new(50);
    for value in [30, 70, 20, 40, 60, 80] {
        root.insert(value);
    }
    println!("{:?}", inorder(&root)); // [20, 30, 40, 50, 60, 70, 80]
}

How it works

Under the hood: the functions new, insert, inorder and main.

Repetition is confined to while current.is_some() || !stack.is_empty() — the rest of the file is straight-line. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Points of care

  • Only the runtime is needed — no packages to fetch and no installs.

Using it

Signature: fn new(value: i32) -> Self

main is the driver: it invokes new, insert and inorder before returning.

Key statements worth quoting

Ordering::Greater => match self.right {
    Some(ref mut child) => child.insert(value),
    None => self.right = Some(Box::new(Node::new(value))),
},
Ordering::Less => match self.left {
    Some(ref mut child) => child.insert(value),
    None => self.left = Some(Box::new(Node::new(value))),
},
while let Some(node) = current {
    stack.push(node);
    current = node.left.as_deref();
}

Interactive Tools for This Topic

FAQ

How do you run Iterative Inorder Walk With Stack?
The runtime alone is enough: execute the file as a complete program.