LeetCode in Swift: Binary Tree Postorder Traversal

Problem Statement

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

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

return [3,2,1].

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 Postorder Depth-first traversal (aka Left-Right-Node (LRN) traversal) of a binary search tree:

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

Obviously, using recursion to write the LRN 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 LRN version of Swift code cost 21 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.8 ms vs 3.5 ms. Swift has done a great job at optimising the recursion. The slower speed of iterative LRN 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 Postorder Traversal1.694ms Save  (1866) Save  (1836)

More Problems Solved in Swift

My full list of LeetCode problems attempted using Swift