
Sponsored
Sponsored
The recursive approach naturally aligns with the definition of preorder traversal: visit the root first, then recursively traverse the left subtree, followed by the right subtree.
Time Complexity: O(N) where N is the number of nodes, as each node is visited once. Space Complexity: O(N) in the worst case due to recursion stack space.
1function TreeNode(val) {
2 this.val = val;
3 this.left = this.right = null;
4}
5
6var preorderTraversal = function(root) {
7 const res = [];
8 function preorder(node) {
9 if (!node) return;
10 res.push(node.val);
11 preorder(node.left);
12 preorder(node.right);
13 }
14 preorder(root);
15 return res;
16};The JavaScript solution employs a recursive approach with an inner function. It traverses the tree and captures node values in an array.
The iterative approach replaces the recursive call stack with an explicit stack. Nodes are processed in preorder, using a stack to maintain traversal state.
Time Complexity: O(N), since each node is visited once. Space Complexity: O(N), for the stack used to store nodes.
1#
In C, we use an array to simulate a stack, manually pushing and popping nodes while traversing the tree. Nodes are visited and added to the result list in prenode order.