私は、バイナリツリーのすべてのノードの座標を計算するために以下の関数を持っています。バイナリツリー内のすべてのノードの座標?
//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用
//Nodes for BST
function Node(val) {
this.value = val;
this.left = null;
this.right = null;
}
//Binary Search Tree
function BST() {
this.root = null;
}
それが残っていけば、それはデクリメントする必要があります。それが右に行くなら増分してください。
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×:-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×:3 Y:-3
出力が正確であるが、このパラメータがどのように再帰で渡され、直感的ではないかと感じる結果でした。誰かが私に何が起こっているのかを明確にすることができますか?これについてもっと直感的な方法がありますか?
ように私は、パラメータとしてインクリメンタのあなたの奇妙な使用に問題が発生したノードは、同じ「座標」を持つことができるので、
x
は、誤解を招くおそれがあります。 –Ehh。値を保存するのが最も一般的な方法ではありませんが、かなり便利です。 – insertmike