c++ - 二叉搜索树计算节点的坐标

标签 c++ algorithm data-structures tree traversal

我需要获取所有节点的x,y坐标,例如:

        10
   8        15
7    9     13

X:访问中序遍历的节点之前已经访问过的节点数

Y:节点距离根的深度

例如对于节点15,x=5(15之前:已经访问过7、8、9、10、13),y=1(第二层)

树没有父指针

int inorder(Node *node, int x) {

    if (node->left)
        x = inorder(node->left, x);
    x++;
    if (node->right)
        inorder(node->right, x);
    return x;
}



int x0(Node *node) {
    return inorder(node, -1);
}



int findY(Node *node, Node *from) {

    if (node == from)
        return 0;
    else if (node->item < from->item)
        return findY(node, from->left) + 1;
    else
        return findY(node, from->right) + 1;
}

int y0(Node *node) {
    return findY(node, theRoot);
}

结果:x错,y对

打印:

void printCoord() {

    queue<Node*> q;
    q.push(theRoot);


    int curLevel = 0;
    while (q.size() > 0) {
        Node *n = q.front();
        q.pop();

        int x = x0(n);
        int y = y0(n);

        if (y > curLevel) {
            curLevel = y;
            cout << endl;
        }

        cout << n->item << "(" << x << "," << y <<")";
        if (n->left)
            q.push(n->left);
        if (n->right)
            q.push(n->right);
    }

}







AvlTree tree;
tree.insertBalance(10);
tree.insertBalance(8);
tree.insertBalance(15);
tree.insertBalance(7);
tree.insertBalance(9);
tree.insertBalance(13);


tree.printCoord();

结果:

10(2,0)
8(1,1)15(1,1)
7(0,2)9(0,2)13(0,2)

我试过了(我认为这不正确,因为右子树遍历不计入该节点)

int inorder(Node *node, int x) {

    if (node->left)
        x = inorder(node->left, x);
    x++;
    if (node->right)
        x = inorder(node->right, x);
    return x;
}

结果是

10(5,0)
8(2,1)15(1,1)
7(0,2)9(0,2)13(0,2)

最佳答案

// your inorder function is not correct
bool inorder(Node* node, int* x, Node* root) {
    if (root==NULL)
        return false;

    if (inorder(node, x, root->left))
        return true;

    if (node==root) //inorder property here
        return true;

    (*x)++;

    if (inorder(node, x, root->right))
        return true;

    return false;

}

int x0(Node *node) {
    int x=0;
    if (inorder(node, &x, theRoot)) //you did't pass root here
        return x;
    else //not found
        return -1;

}

积分:

  1. 您没有通过根并与查询节点核对。那是不正确的。您需要从根开始搜索树。
  2. 对于任何有序属性,基本思想是向左走,做你想做的事,然后向右走。但这可能会因您的问题而异。
  3. 如果找到查询节点,则不再进行inorder 调用。它一直返回到 x0,其中 x 包含所需的值。

关于c++ - 二叉搜索树计算节点的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23453172/

相关文章:

python - 如何在python中编辑拼接模块的opencv源代码?

c++ - 如何在 C++ 中编写简短的文字?

python - 如何保持在 GAE 配额之下?算法设计

algorithm - 新的 Windows 10 放大镜使用什么算法?

data-structures - 二叉搜索树的定义中是否允许重复键?

Python- "in"和 "in x for x in"有什么区别

c++ - 为什么thread_local不能应用于非静态数据成员以及如何实现线程局部非静态数据成员?

c++ - 在 C++ 中使用类模板作为回调

java - 如何比较第一个元素和最后一个元素按降序对数组进行排序

algorithm - 红黑树删除未知行为