【发布时间】:2016-11-18 14:29:55
【问题描述】:
我有以下函数来计算二叉树中每个节点的坐标。
//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
输出是正确的,但这是摆弄参数如何通过递归传入的结果,感觉不直观。有人可以帮我澄清发生了什么吗?有没有更直观的方法来解决这个问题?
【问题讨论】:
-
我对你奇怪地使用增量器作为参数有疑问。
-
嗯。这不是最传统的保存值的方法,但非常方便。
标签: javascript tree coordinates binary-tree binary-search-tree