Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Iterative Binary Tree Traversal Implementations

Tech 1

Recursive mechanisms rely on the system call stack to manage state, storing local variables and return addresses during each call. This behavior can be replicated manually using an explicit stack data structure to perform tree traversals iteratively.

Preorder Traversal

Preorder traversal follows the sequence: Root, Left, Right. To simulate this iteratively, push the root node onto the stack first. When popping nodes, process the current node, then push its children. Since stacks operate on a Last-In-First-Out (LIFO) basis, push the right child before the left child. This ensures the left child is popped and processed before the right child.

class Solution {
public:
    std::vector<int> preorderTraversal(TreeNode* root) {
        std::vector<int> output;
        std::stack<TreeNode*> nodeStack;
        
        if (root == nullptr) return output;
        
        nodeStack.push(root);
        while (!nodeStack.empty()) {
            TreeNode* current = nodeStack.top();
            nodeStack.pop();
            output.emplace_back(current->val);
            
            if (current->right != nullptr) {
                nodeStack.push(current->right);
            }
            if (current->left != nullptr) {
                nodeStack.push(current->left);
            }
        }
        return output;
    }
};

Inorder Traversal

Inorder traversal follows the sequnece: Left, Root, Right. This requires traversing to the deepest left node first. Use a pointer to iterate down the left subtree, pushing each node onto the stack. Once the leftmost node is reached, pop from the stack, process the value, and move the pointer to the right child.

class Solution {
public:
    std::vector<int> inorderTraversal(TreeNode* root) {
        std::vector<int> output;
        std::stack<TreeNode*> nodeStack;
        TreeNode* iterator = root;
        
        while (iterator != nullptr || !nodeStack.empty()) {
            while (iterator != nullptr) {
                nodeStack.push(iterator);
                iterator = iterator->left;
            }
            iterator = nodeStack.top();
            nodeStack.pop();
            output.emplace_back(iterator->val);
            iterator = iterator->right;
        }
        return output;
    }
};

Postorder Traversal

Postorder traversal follows the sequence: Left, Right, Root. A common iterative approach modifies the preorder logic. By changing the push order to Left then Right, the pop order becomes Root, Right, Left. Reversing the resulting collection yields the desired Left, Right, Root sequence.

class Solution {
public:
    std::vector<int> postorderTraversal(TreeNode* root) {
        std::vector<int> output;
        std::stack<TreeNode*> nodeStack;
        
        if (root == nullptr) return output;
        
        nodeStack.push(root);
        while (!nodeStack.empty()) {
            TreeNode* current = nodeStack.top();
            nodeStack.pop();
            output.emplace_back(current->val);
            
            if (current->left != nullptr) {
                nodeStack.push(current->left);
            }
            if (current->right != nullptr) {
                nodeStack.push(current->right);
            }
        }
        std::reverse(output.begin(), output.end());
        return output;
    }
};

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.