🧠
Iterative DFS Using Stack
💡 Using an explicit stack instead of recursion helps avoid stack overflow and shows mastery of DFS traversal techniques.
Intuition
Simulate the recursive DFS with a stack that stores pairs of nodes and the current number formed so far, processing nodes iteratively.
Algorithm
- Initialize a stack with the root node and initial number 0.
- While stack is not empty, pop a node and current number.
- Update current number by appending node's digit.
- If node is leaf, add current number to total sum.
- Otherwise, push non-null children with updated numbers onto stack.
💡 The key is to maintain the current number alongside each node in the stack to correctly accumulate values.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
if not root:
return 0
total = 0
stack = [(root, 0)]
while stack:
node, current_number = stack.pop()
current_number = current_number * 10 + node.val
if not node.left and not node.right:
total += current_number
if node.right:
stack.append((node.right, current_number))
if node.left:
stack.append((node.left, current_number))
return total
# Example usage:
# root = TreeNode(1, TreeNode(2), TreeNode(3))
# print(Solution().sumNumbers(root)) # Output: 25
Line Notes
if not root:Handle empty tree edge case
stack = [(root, 0)]Initialize stack with root and initial number 0
while stack:Process nodes until stack is empty
node, current_number = stack.pop()Pop node and current number from stack
current_number = current_number * 10 + node.valAppend current node's digit to current number
if not node.left and not node.right:If leaf, add current number to total
stack.append((node.right, current_number))Push right child with updated number if exists
stack.append((node.left, current_number))Push left child with updated number if exists
return totalReturn total sum after traversal
import java.util.Stack;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class Solution {
public int sumNumbers(TreeNode root) {
if (root == null) return 0;
int total = 0;
Stack<Pair<TreeNode, Integer>> stack = new Stack<>();
stack.push(new Pair<>(root, 0));
while (!stack.isEmpty()) {
Pair<TreeNode, Integer> p = stack.pop();
TreeNode node = p.getKey();
int currentNumber = p.getValue() * 10 + node.val;
if (node.left == null && node.right == null) {
total += currentNumber;
}
if (node.right != null) {
stack.push(new Pair<>(node.right, currentNumber));
}
if (node.left != null) {
stack.push(new Pair<>(node.left, currentNumber));
}
}
return total;
}
// Example usage:
// public static void main(String[] args) {
// TreeNode root = new TreeNode(1);
// root.left = new TreeNode(2);
// root.right = new TreeNode(3);
// System.out.println(new Solution().sumNumbers(root)); // 25
// }
}
// Note: Pair class can be imported from javafx.util.Pair or custom implemented.
Line Notes
if (root == null) return 0;Handle empty tree edge case
Stack<Pair<TreeNode, Integer>> stack = new Stack<>();Initialize stack to hold nodes and current numbers
stack.push(new Pair<>(root, 0));Push root with initial number 0
while (!stack.isEmpty()) {Process nodes until stack is empty
Pair<TreeNode, Integer> p = stack.pop();Pop node and current number
int currentNumber = p.getValue() * 10 + node.val;Append node's digit to current number
if (node.left == null && node.right == null)If leaf, add current number to total
stack.push(new Pair<>(node.right, currentNumber));Push right child if exists
stack.push(new Pair<>(node.left, currentNumber));Push left child if exists
return total;Return total sum after traversal
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int sumNumbers(TreeNode* root) {
if (!root) return 0;
int total = 0;
stack<pair<TreeNode*, int>> stk;
stk.push({root, 0});
while (!stk.empty()) {
auto [node, currentNumber] = stk.top();
stk.pop();
currentNumber = currentNumber * 10 + node->val;
if (!node->left && !node->right) {
total += currentNumber;
}
if (node->right) stk.push({node->right, currentNumber});
if (node->left) stk.push({node->left, currentNumber});
}
return total;
}
};
// Example usage:
// int main() {
// TreeNode* root = new TreeNode(1);
// root->left = new TreeNode(2);
// root->right = new TreeNode(3);
// Solution sol;
// cout << sol.sumNumbers(root) << endl; // 25
// return 0;
// }
Line Notes
if (!root) return 0;Handle empty tree edge case
stack<pair<TreeNode*, int>> stk;Stack holds pairs of nodes and current numbers
stk.push({root, 0});Push root with initial number 0
while (!stk.empty()) {Process nodes until stack is empty
auto [node, currentNumber] = stk.top();Pop node and current number
currentNumber = currentNumber * 10 + node->val;Append node's digit to current number
if (!node->left && !node->right)If leaf, add current number to total
stk.push({node->right, currentNumber});Push right child if exists
stk.push({node->left, currentNumber});Push left child if exists
return total;Return total sum after traversal
function TreeNode(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
var sumNumbers = function(root) {
if (!root) return 0;
let total = 0;
let stack = [[root, 0]];
while (stack.length > 0) {
let [node, currentNumber] = stack.pop();
currentNumber = currentNumber * 10 + node.val;
if (!node.left && !node.right) {
total += currentNumber;
}
if (node.right) stack.push([node.right, currentNumber]);
if (node.left) stack.push([node.left, currentNumber]);
}
return total;
};
// Example usage:
// const root = new TreeNode(1, new TreeNode(2), new TreeNode(3));
// console.log(sumNumbers(root)); // 25
Line Notes
if (!root) return 0;Handle empty tree edge case
let stack = [[root, 0]];Initialize stack with root and initial number 0
while (stack.length > 0) {Process nodes until stack is empty
let [node, currentNumber] = stack.pop();Pop node and current number
currentNumber = currentNumber * 10 + node.val;Append node's digit to current number
if (!node.left && !node.right)If leaf, add current number to total
stack.push([node.right, currentNumber]);Push right child if exists
stack.push([node.left, currentNumber]);Push left child if exists
return total;Return total sum after traversal
Each node is visited once, so time is O(n). The stack holds at most h nodes, where h is tree height, so space is O(h).
💡 For a tree with 1000 nodes and height 10, this means about 1000 operations and stack size up to 10.
Interview Verdict: Accepted
This approach avoids recursion depth issues and is useful in languages with limited recursion stack.