TypeError:无法读取未定义的属性“ left”

时间:2019-06-26 19:06:45

标签: javascript node.js express data-structures queue

    'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

// Complete the roadsAndLibraries function below.
function roadsAndLibraries(n, c_lib, c_road, cities) {
    console.log("roadsAndLibraries n--->", n);
    console.log("roadsAndLibraries c_lib--->", c_lib);
    console.log("roadsAndLibraries c_road--->", c_road);
    console.log("roadsAndLibraries cities--->", cities);
    var m = new Map();
    m.set('a', 2);
    m.set('b', 3);
    m.set('b', 3);
    m.set('b', 2);
    m.set('b', 1);

    console.log("map value--->", m);
        // Check that a root node exists.

    // if (rootNode === null) {
    //     return;
    // }

    // Check that a root node exists.
    if (n === null) {
        console.log("n root node--->", n);
        return;
    }

    // Create our queue and push our root node into it.
    // var queue = [];
    // queue.push(rootNode);

    // Create our queue and push our root node into it.
    var queue = [];
    queue.push(n);

    console.log(" queue.push--->", queue);


    while (queue.length > 0) {
        // Create a reference to currentNode, at the top of the queue.
        var currentNode = queue[0];

        // If currentNode has a left child node, add it to the queue.
        if (currentNode.left !== null) {
            queue.push(currentNode.left)
        }
        // If currentNode has a right child node, add it to the queue.
        if (currentNode.right !== null) {
            queue.push(currentNode.right)
        }
        // Remove the currentNode from the queue.
        queue.shift()
    }




}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
    console.log("ws--->", ws);


    const q = parseInt(readLine(), 10);
    console.log("q--->", q);

    for (let qItr = 0; qItr < q; qItr++) {
        const nmC_libC_road = readLine().split(' ');
        console.log("nmC_libC_road--->", nmC_libC_road);

        const n = parseInt(nmC_libC_road[0], 10);
        console.log("n--->", n);


        const m = parseInt(nmC_libC_road[1], 10);
        console.log("m--->", m);

        const c_lib = parseInt(nmC_libC_road[2], 10);
        console.log("c_lib--->", c_lib);

        const c_road = parseInt(nmC_libC_road[3], 10);
        console.log("c_road--->", c_road);

        let cities = Array(m);
        console.log("cities--->", cities);

        for (let i = 0; i < m; i++) {
            cities[i] = readLine().split(' ').map(citiesTemp => parseInt(citiesTemp, 10));
        }

        const result = roadsAndLibraries(n, c_lib, c_road, cities);
        console.log("result--->", result);

        ws.write(result + '\n');
    }

    ws.end();
}

编译后

Input (stdin)Download
2
3 3 2 1
1 2
3 1
2 3
6 6 2 5
1 3
3 4
2 4
1 2
2 3
5 6
Your Output (stdout)
~ no response on stdout ~
Expected OutputDownload
4
12
Debug output
ws---> WriteStream {
  _writableState:
   WritableState {
     objectMode: false,
     highWaterMark: 16384,
     finalCalled: false,
     needDrain: false,
     ending: false,
     ended: false,
     finished: false,
     destroyed: false,
     decodeStrings: true,
     defaultEncoding: 'utf8',
     length: 0,
     writing: false,
     corked: 0,
     sync: true,
     bufferProcessing: false,
     onwrite: [Function: bound onwrite],
     writecb: null,
     writelen: 0,
     bufferedRequest: null,
     lastBufferedRequest: null,
     pendingcb: 0,
     prefinished: false,
     errorEmitted: false,
     emitClose: false,
     bufferedRequestCount: 0,
     corkedRequestsFree:
      { next: null,
        entry: null,
        finish: [Function: bound onCorkedFinish] } },
  writable: true,
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  path:
   '/tmp/submission/20190702/20/31/hackerrank-d27db21d31abaff7353d49d7e433da3a/0.userout',
  fd: null,
  flags: 'w',
  mode: 438,
  start: undefined,
  autoClose: true,
  pos: undefined,
  bytesWritten: 0,
  closed: false }
q---> 2
nmC_libC_road---> [ '3', '3', '2', '1' ]
n---> 3
m---> 3
c_lib---> 2
c_road---> 1
cities---> [ <3 empty items> ]
roadsAndLibraries n---> 3
roadsAndLibraries c_lib---> 2
roadsAndLibraries c_road---> 1
roadsAndLibraries cities---> [ [ 1, 2 ], [ 3, 1 ], [ 2, 3 ] ]
map value---> Map { 'a' => 2, 'b' => 1 }
 queue.push---> [ 3 ]

4 个答案:

答案 0 :(得分:3)

const n = parseInt(nmC_libC_road[0], 10);
console.log("n--->", n);

queue是一个包含n的数组,n是一个数字,不能用作对象。我认为是问题所在。

因此,我认为您需要将n更改为m

答案 1 :(得分:2)

您的直接问题是queue.push(currentNode.left)(和queue.push(currentNode.right))被作为nullundefined are different in javascript执行。在循环的第二次,队列中将有两个未定义的元素,currentNode现在将是未定义的,因此,您当然不能访问未定义的leftright属性。

为什么会这样?基本上,您还没有完成将中型代码的BFS实现转换为HackerRank所需的功能。 BFS代码期望队列包含节点对象,并且HackerRank的输入绝对不是类似于节点的任何东西。按照目前的状态,队列中唯一的项目是一个数字,其中不包含任何leftright属性。该练习将至少涉及将其输入转换为适合BFS的节点结构(如果BFS甚至是合适的解决方案)。

一个可能的解决方案可能是扩展null检查,使其也包含undefined。另一个可能是确保进入队列的所有内容都是正确的节点,并且具有初始化的leftright值,即使该值是null。对于中间测试,我希望将queue.push(n);替换为let aBoringNode = {left: null, right: null}; queue.push(aBoringNode);至少可以使您摆脱当前错误并执行有效的BFS执行(如果非常无聊)。

答案 2 :(得分:0)

只是一个猜测,但是请记住,在JavaScript中,undefined和null不是同一回事。因此,未定义!== null是真实的。在循环中,应添加检查以确保currentNode.right和currentNode.left不是未定义的

答案 3 :(得分:0)

只需扫描问题描述,它就会说:

  

roadsAndLibraries具有以下参数:

     

n:整数,城市数

但是显然在您的代码中,您将n视为“节点” ... 确实是javascript所指示的'TypeError'。