【问题标题】:Maximum Depth of N-ary Tree when use BFS使用 BFS 时 N-ary Tree 的最大深度
【发布时间】:2019-01-25 23:40:03
【问题描述】:

为了得到nary-tree的最大深度,下面这段代码是正确的答案。

var maxDepth = function(root) {
 if (!root) {
    return 0
 }
 let depth = 0;
 let arr=[root];

 while (arr.length) {
    let arrlength=arr.length;
    for (let i=0;i<arrlength;i++) {
        let curr=arr.shift();
        arr.push(...curr.children);           
    }
    depth++;
 }
 return depth;

};

但是,如果我在 for 循环中使用 arr.length 而不是使用“let arrlength=arr.length;”并使用arrlength,这将是一个错误的答案...... 我可以知道为什么吗?我说不出有什么区别。非常感谢!

var maxDepth = function(root) {
 if (!root) {
    return 0
 }
 let depth = 0;
 let arr=[root];

 while (arr.length) {       
    for (let i=0;i<arr.length;i++) {
        let curr=arr.shift();
        arr.push(...curr.children);           
    }
    depth++;
 }
 return depth;

};

可以在这里测试: https://leetcode.com/problems/maximum-depth-of-n-ary-tree/

【问题讨论】:

  • arr.shift() 改变数组的长度。
  • 这是呼吸第一。

标签: javascript algorithm data-structures tree breadth-first-search


【解决方案1】:

let curr = arr.shift() 从数组中删除第一个元素并将其分配给curr

arr.push(...curr.children) 将所有子元素添加到数组的末尾。

这两个操作都会更改数组长度,并且测试i &lt; arr.length 每次都使用当前长度。但是循环只应该处理原始数组元素。 arrlength 包含循环前数组的原始长度。它不会随着数组的修改而改变,因此循环将运行正确的次数。

如果您在循环之前复制了arr,则可以在循环中使用.length,并对其进行循环,而不是修改您正在循环的数组。

var maxDepth = function(root) {
  if (!root) {
    return 0
  }
  let depth = 0;
  let arr = [root];

  while (arr.length) {
    let copy = [...arr];
    arr.splice(0, arr.length);
    for (let i = 0; i < copy.length; i++) {
      let curr = copy[i];
      arr.push(...curr.children);
    }
    depth++;
  }
  return depth;

};

const tree = {
  value: 1,
  children: [{
      value: 3,
      children: [{
        value: 5,
        children: []
      }, {
        value: 6,
        children: []
      }]
    },
    {
      value: 2,
      children: []
    },
    {
      value: 3,
      children: []
    }
  ]
};

console.log(maxDepth(tree));

【讨论】:

  • 啊!太感谢了!我很困惑哈哈!所以我们需要这个来存储原始长度,因为在我们 push/shift 之后 for 循环中的每次迭代,数组的长度都会改变,如果我们不使用变量来存储它,for 循环会将 i 与每次都有新的长度对吗? :D 非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 2021-11-22
  • 2015-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多