【问题标题】:TypeError: Cannot read property 'left' of undefinedTypeError:无法读取未定义的属性“左侧”
【发布时间】:2019-11-08 19:08:58
【问题描述】:
    '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 ]

【问题讨论】:

  • stdin 的输入是什么?你也可以包括它吗?
  • @FZs 也更新了输出...如果我给了你正确的信息,你能告诉我吗

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


【解决方案1】:

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

【讨论】:

  • 嘿更新了问题中的整个代码,你们能更新代码吗...好混乱:(
【解决方案2】:

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

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

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

【讨论】:

  • 嘿更新了问题中的整个代码,你们能更新代码吗...好混乱:(
【解决方案3】:

刚刚扫描了问题描述,上面写着:

roadsAndLibraries 有以下参数:

n:整数,城市数量

但显然在您的代码中,您将 n 视为“节点”... 正如 javascript 所示,这确实是一个“TypeError”。

【讨论】:

  • 嘿更新了问题中的整个代码,你们能更新代码吗...好混乱:(
【解决方案4】:
const n = parseInt(nmC_libC_road[0], 10);
console.log("n--->", n);

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

所以,我认为您需要将 n 改为 m

【讨论】:

  • 其他人指出n 不是节点,以及如何导致错误被抛出。 m 也不是具有 leftright 属性的节点,因此将 n 更改为 m 不会有帮助。
猜你喜欢
  • 2013-03-10
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多