LeetCode in Swift: Binary Tree Level Order Traversal

Problem Statement

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

return its level order traversal as:

Original LeetCode problem page

My Solution in Swift

This is how TreeNode class looks like:

I used tail recursion technique to make the recursive approach faster. The following is my recursive version of Breadth-first traversal (aka level order traversal) of a binary search tree:

The iterative version of Breadth-first traversal (aka level order traversal) of a binary search tree:

Even using -O compilation flag, the recursive version is still slower than the iterative counterpart with 33 ms vs 6 ms. This doesn’t follow behaviours as depicted in Depth-first traversals (NLR, LNR, LRN). The main reason is that the recursive version has to pass intermediate results deep down along with those recursive function calls. Besides, the overhead of function calls is not negligible.

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 Level Order Traversal5.631ms Save  (1864) Save  (1956)

More Problems Solved in Swift

My full list of LeetCode problems attempted using Swift