HackerRank – Tree: Preorder Traversal Solution in JavaScript

Tree: Preorder Traversal is a coding challenge with easy difficulty in the HackerRank data structures category. In this blog post, we’ll discuss how we can solve it in JavaScript in O(n) time and O(1) space.

Problem Statement

Complete the preOrder function in the editor below, which has  parameter: a pointer to the root of a binary tree. It must print the values in the tree’s preorder traversal as a single line of space-separated values.

Read full details and access the challenge on Tree: Preorder Traversal | HackerRank


function preOrder(root) {
    if (root) {
        process.stdout.write(root.data + ' ');

Time Complexity : O(n)

Space Complexity : O(1)

The key to solve this challenge is by using recursion. We keep printing the data and recalling the function with left and right as the parameter and eventually stop when there are no more nodes left.

We’re visiting all the nodes and use no extra data structure so we have O(n) time and O(1) space complexity.


That’s how you can solve the Tree: Preorder Traversal Challenge in HackerRank.

This is a basic skill on trees, so it is a nice challenge to improve our understanding.

If you have another approach different from mine, please do comment below!

Check out the rest of my blog for more helpful contents on Data Structures and Algorithms in JavaScript! We’ll also discuss more HackerRank solutions in JavaScript for the upcoming posts!

See you next post!

Leave a Comment