【问题标题】:Simple merge two binary trees question JS简单合并两棵二叉树问题JS
【发布时间】:2021-09-08 10:29:00
【问题描述】:

我想知道为什么这个解决方案适用于 LeetCode,因为当我在控制台中记录函数的输出时,它对我来说似乎是一堆废话:[ 1, 3, 2, 5, val: NaN, left: undefined, right: undefined ] 这与 LeetCode 上显示的输出不同。

我是编程新手,非常感谢您的帮助!

问题: LeetCode

我不明白的代码:

 const mergeTrees = (t1, t2) => {
     
    if (!t1) {
        return t2;
    }
    if (!t2) {
        return t1;
    }
    t1.val += t2.val;
    t1.left = mergeTrees(t1.left, t2.left);
    t1.right = mergeTrees(t1.right, t2.right);

    return t1;
  
};

console.log(mergeTrees([1,3,2,5],
        [2,1,3,null,4,null,7]))

leetcode 输出:[3,4,5,5,4,null,7]

我的 console.log 输出:[ 1, 3, 2, 5, val: NaN, left: undefined, right: undefined ]

【问题讨论】:

  • 你能把代码贴在这里吗?
  • 你是对的。没有意义
  • 你在哪里找到这个解决方案?

标签: javascript binary-tree


【解决方案1】:

这对我来说更有意义 可以试试吗?

如果您将 t1 和 t2 视为线,并将它们堆叠起来,您可以简单地逐列添加值。并保持空值。

var t1 = [1, 3, 2, 5]
var t2 = [2, 1, 3, null, 4, null, 7]

var i = 0;
var t = [];
while (typeof t1[i] !== 'undefined' || typeof t2[i] !== 'undefined') {
    // keeps nulls and undefined
    if ((t1[i] === null || typeof t1[i] === 'undefined') && (t2[i] === null || typeof t2[i] === 'undefined'))
        t[i] = null;
    // just add values
    else
        t[i] = (t1[i]||0) + (t2[i]||0);
    // got to next step
    i++;
}

console.log(t)
// [3, 4, 5, 5, 4, null, 7]

【讨论】:

  • 感谢您的回答,我觉得它看起来很棒!但我主要是好奇为什么该代码可以在 leetcode 上运行,但日志却很奇怪:(
  • 然后写信给网站创建者。这对我来说只是一个简单的错误。
猜你喜欢
  • 2020-10-19
  • 1970-01-01
  • 2015-12-20
  • 2019-11-13
  • 2014-09-24
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
相关资源
最近更新 更多