Home > OS >  How to stdout Hackerrank Binary Tree question in TypeScript?
How to stdout Hackerrank Binary Tree question in TypeScript?

Time:04-29

Here is the Hackerrank question:


Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function and print the values in a single line separated by a space.


I already defined the function levelOrder(). However don't know how to stdout. Also why is no Node class is given here. When I checked other languages like Java for this question, I saw that Node class was declared. How can they expect me to take strings as, act as they are nodes. I am confused.

Here is entire code in the hackerrank editor including their setup:

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString: string = '';
let inputLines: string[] = [];
let currentLine: number = 0;
process.stdin.on('data', function(inputStdin: string): void {
    inputString  = inputStdin;
});

process.stdin.on('end', function(): void {
    inputLines = inputString.split('\n');
    inputString = '';
    main();
});

function readLine(): string {
    return inputLines[currentLine  ];
}

function main() {
    // Enter your code here
    
    function levelOrder(root: any): string {
        const queue = [root];
        let visited = "";
        let currentNode = root;
        while (queue.length > 0) {
            currentNode = queue.shift();
            visited  = `${currentNode.val} `;
            if (currentNode.left) queue.push(currentNode.left);
            if (currentNode.right) queue.push(currentNode.right);
        }
        return visited;
    }
    // How I am going to invoke my function and stdout return val here?
}

CodePudding user response:

You are right that this is confusing.

Apparently, HackerRank has not really put much effort in the TypeScript versions of the code challenges, as there is no provision in the template code for converting the text input into a TreeNode data structure, like is done for the other languages.

Secondly, the challenge does not explain either how the text based input is organised. For this, I looked at some other binary tree challenges on HackerRank, and found that for this one that input format is described:

The first line contains an integer

  • Related