二叉树中每个节点的坐标?
Coordinates of every node in a binary 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: " + node.value + " x: " + x + " y: " + y);
nodeCoordinates(node.left, --x, --y);
nodeCoordinates(node.right, x+=2, y--);
}
节点和树(BST):
//Nodes for BST
function Node(val) {
this.value = val;
this.left = null;
this.right = null;
}
//Binary Search Tree
function BST() {
this.root = null;
}
对于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
是树的级别,低于零。
x
是误导,因为节点可以有相同的"coordinates",比如
Node: 30 x: 0 y: -2
Node: 55 x: 0 y: -2
我有以下函数来计算二叉树中每个节点的坐标。
//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):
//Nodes for BST
function Node(val) {
this.value = val;
this.left = null;
this.right = null;
}
//Binary Search Tree
function BST() {
this.root = null;
}
对于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
是树的级别,低于零。
x
是误导,因为节点可以有相同的"coordinates",比如
Node: 30 x: 0 y: -2 Node: 55 x: 0 y: -2