【问题标题】:Coordinates of every node in a binary tree?二叉树中每个节点的坐标?
【发布时间】: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


【解决方案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

【讨论】:

  • 只是一个建议,当从零开始对每个节点进行编号时,您可以使用数字表示来处理每个节点,并首先在同一级别上为每个节点递增,然后再进入下一个级别。例如level 0是0,level 1有节点号1和2,level 2有3、4、5、6,snd等等。
  • 感谢您的帮助!在这种情况下,与使用文字的操作相比,递增/递减的行为是否存在差异?另外,是的,看起来我必须重新定义 x 是什么,也许会同意你的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多