2016-11-18 175 views
1

我有以下函數來計算二叉樹中每個節點的座標。二叉樹中每個節點的座標?

//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×:0 Y:0
  • 節點:20×:-1 Y:-1
  • 節點:10×: -2 Y:-2
  • 節點:30×:0 Y:-2
  • 節點:60×:1個Y:-1
  • 節點:55 X:0 Y:-2
  • 節點:70×:2 Y:-2
  • 節點:65 X:1個Y:-3
  • 節點:80×:3 Y:-3

輸出是正確的,但本是擺弄參數如何通過遞歸傳遞的結果,它感覺不直觀。有人能幫我澄清一下發生了什麼嗎?有沒有更直觀的方法可以解決這個問題?

+0

我有你的怪使用增量器作爲參數的問題。 –

+0

呃。這不是保存價值的最常規方式,但非常方便。 – insertmike

回答

1

我會改變參數處理,而不使用賦值或增量運算符。

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是一種誤導,因爲節點可以有相同的「座標」,像

Node: 30 x: 0 y: -2 
Node: 55 x: 0 y: -2 
+0

只是一個建議,當從零開始爲每個節點編號時,可以用數字表示來處理每個節點,並且首先爲同一級別上的每個節點遞增,然後進入下一級。例如等級0爲0,等級1具有節點號碼1和2,等級2具有3,4,5,6等等。 –

+0

感謝您的幫助!在這種情況下,與文字操作相比,增加/減少行爲有什麼不同?另外,是的,它看起來像我必須重新定義x是什麼,也許跟你的建議一起。 – insertmike