【问题标题】:How do I traverse through this tree(not a binary search tree)?如何遍历这棵树(不是二叉搜索树)?
【发布时间】:2022-11-02 21:24:22
【问题描述】:

注意:我使用递归

我想遍历这棵树(所有节点/对象),并可能将它们添加到数组中或稍微调整它们或其他东西。 我正在尝试创建一个国际象棋游戏板(甚至不确定我是否在正确的轨道上)。 棋盘上的每个块都是一个对象(节点),其属性包括具有块的 x 和 y 坐标的数组,块位于其右侧、左侧、顶部和底部。 这是树的代码:

 This function creates all the blocks on the board
function Node(pos, top = null, right = null, left = null, bottom = null) {
  this.pos = pos;
  this.top = top;
  this.right = right;
  this.left = left;
  this.bottom = bottom;
}


This function creates the gameboard
function buildBoard(x = 1, y = 1) {
  if(x == 9 || y == 9 || x <= 0 || y <= 0) return null
  else {
    const root = new Node([x, y])
    root.right = buildBoard(x += 1, y);
    x -= 1;
    root.top = buildBoard(x, y += 1);
    return root
  }
}

我试着遍历这棵树,就好像它是一棵二叉树一样,它有点工作。 由于这棵树基本上是棋盘上的所有块(8x8),所以块的总数应该是 64,但是当我以与二叉树相同的方式遍历它时,它给了我数千个节点

【问题讨论】:

    标签: javascript recursion tree binary-tree binary-search-tree


    【解决方案1】:

    首先,这不是一棵树。它是一个循环图。

    主要问题是您的代码将创建坐标为 2、2 的节点两次,因为它通过两条路线到达那里:先向右然后向下,或者先向下然后向右。创建的节点离原点越远,情况就越糟糕:对于由右/下步骤组成的每条可能的路径,都会创建一个节点,从而导致大量节点具有相同的坐标。

    以下是如何正确执行此操作:

    class Node {
        constructor(pos, bottom=null, right=null) {
            this.pos = pos;
            this.bottom = bottom;
            this.right = right;
            this.top = null;
            this.left = null;
            if (bottom) bottom.top = this; // back reference
            if (right) right.left = this; // back reference
        }
    }
    
    
    function buildBoard() {
        const row = Array(10).fill(null);
        for (let y = 8; y; y--) {
            for (let x = 8; x; x--) {
                row[x] = new Node([x, y], row[x], row[x + 1]);
            }
        }
        return row[1]; // cell at [1, 1]
    }
    
    let a1 = buildBoard();
    // Verify that two different paths to the same coordinates, lead to the
    // same node:
    console.log(a1.right.right.bottom.bottom 
            === a1.bottom.right.right.right.bottom.left);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      相关资源
      最近更新 更多