LeetCode in Swift: Binary Tree Preorder Traversal

Problem Statement

Given a binary tree, return the preorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

Original LeetCode problem page

My Solution in Swift

This is how TreeNode class looks like:

The recursive version of Preorder Depth-first traversal (aka Node-Left-Right (NLR) traversal) of a binary search tree:

The iterative version of Preorder Depth-first traversal (aka Node-Left-Right (NLR) traversal) of a binary search tree:

Obviously, using recursion to write the NLR is more straightforward. On the other hand, using iteration seems more efficient, because we don’t have to worry about those call stacks introduced by the recursion. Indeed, under debug mode (with -Onone compilation flag), the recursive and iterative NLR version of Swift code cost 19 ms and 12 ms respectively. The iterative version is about twice as fast as the recursive counterpart. However, when compiling with -O flag, the recursive version runs almost twice as fast as the iterative counterpart with execution time 1.4 ms vs 3.6 ms. Swift has done a great job at optimising the recursion. The slower speed of iterative NLR approach may be caused by my using of a hashset to keep record of what TreeNodes have been visited, in order to make sure that each TreeNode is only visited once. This also tries to make the traversal process non-destructive, so the process doesn’t change the content of the tree being traversed.

Try It Yourself

1: each links to a blog post of mine that is dedicated to the problem
2: total execution time of a solution on my MacBook Pro (Late 2013, 2.6 GHz Intel Core i7, 16 GB 1600 MHz DDR3). Each solution is compiled with following command:

$ swiftc -O -sdk `xcrun --show-sdk-path --sdk macosx` json.swift main.swift -o mySolution

The total execution time is the average of 10 runs.
3: these test cases are semi-automatically :P retrieved from LeetCode Online Judge system and are kept in JSON format
4: each Xcode project includes everything (my Swift solution to a problem, its JSON test cases and a driver code to test the solution on those test cases)

Problem1Time2Test Cases3My Xcode Project4
Binary Tree Preorder Traversal1.339ms Save  (1798) Save  (1802)

More Problems Solved in Swift

My full list of LeetCode problems attempted using Swift