【发布时间】: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