Javascript 二叉树中每个节点的坐标?
我有以下函数来计算二叉树中每个节点的坐标Javascript 二叉树中每个节点的坐标?,javascript,tree,coordinates,binary-tree,binary-search-tree,Javascript,Tree,Coordinates,Binary Tree,Binary Search Tree,我有以下函数来计算二叉树中每个节点的坐标 //x & y parameters should be untouched //root assumed to be 0,0 function nodeCoordinates(node, x, y) { if (x === undefined && y === undefined ) {x = 0; y = 0;} if (!node) {return;} console.log("Node: " +
//x & y parameters should be untouched
//root assumed to be 0,0
function nodeCoordinates(node, x, y)
{
if (x === undefined && y === undefined ) {x = 0; y = 0;}
if (!node) {return;}
console.log("Node: " + node.value + " x: " + x + " y: " + y);
nodeCoordinates(node.left, --x, --y);
nodeCoordinates(node.right, x+=2, y--);
}
节点和树(BST):
对于x,如果它向左移动,它应该减小。如果进展顺利,则递增
对于y,它应该随着水平下降而减小
示例测试代码和输出:
my_BST.insert(50);
my_BST.insert(60);
my_BST.insert(55);
my_BST.insert(20);
my_BST.insert(70);
my_BST.insert(80);
my_BST.insert(10);
my_BST.insert(30);
my_BST.insert(65);
nodeCoordinates(my_BST.root);
- 节点:50 x:0 y:0
- 节点:20 x:-1 y:-1
- 节点:10 x:-2 y:-2
- 节点:30 x:0 y:-2
- 节点:60 x:1 y:-1
- 节点:55 x:0 y:-2
- 节点:70 x:2 y:-2
- 节点:65 x:1 y:-3
- 节点:80 x:3 y:-3
输出是正确的,但这是通过递归处理参数传递方式的结果,感觉不直观。有人能帮我弄清楚发生了什么事吗?有没有更直观的方法来实现这一点?我会更改参数处理,而不使用赋值或增量运算符
function nodeCoordinates(node, x, y) {
x = x || 0;
y = y || 0;
if (!node) {
return;
}
console.log("Node: " + node.value + " x: " + x + " y: " + y);
nodeCoordinates(node.left, x - 1, y - 1);
nodeCoordinates(node.right, x + 1, y - 1);
}
基本上,y
是树的级别,在0以下
x
具有误导性,因为节点可以具有相同的“坐标”,如
我对你奇怪地使用递增函数作为参数有一个问题。这不是保存值的最传统方法,但它非常方便。建议您在对每个节点进行编号时,可以使用数字表示法来处理每个节点,从一开始就使用零编号,并先递增同一级别上的每个节点,然后再转到下一级别。例如,级别0是0,级别1有节点号1和2,级别2有3、4、5、6、snd等等。感谢您的帮助!在这种情况下,与使用文字的操作相比,增量/减量的行为存在差异,这有什么原因吗?而且,是的,看起来我必须重新定义x是什么,也许是按照你的建议。
function nodeCoordinates(node, x, y) {
x = x || 0;
y = y || 0;
if (!node) {
return;
}
console.log("Node: " + node.value + " x: " + x + " y: " + y);
nodeCoordinates(node.left, x - 1, y - 1);
nodeCoordinates(node.right, x + 1, y - 1);
}
Node: 30 x: 0 y: -2
Node: 55 x: 0 y: -2