二进制搜索树计算节点的坐标
Binary search tree compute the coordinate of nodes
我需要得到所有节点的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;
}
点数:
- 您没有传递根,而是使用查询节点进行了检查。这是不对的。你需要从树的根开始搜索
- 对于任何无序的财产,基本的想法是向左走,做你想做的事,然后向右走。但这可能因您的问题而异
- 如果找到查询节点,则不会再进行
inorder
调用。它一直返回到x0
,其中x
包含所需的值
我很确定这一点:
if (node->right)
inorder(node->right, x);
应该是:
if (node->right)
x = inorder(node->right, x);
除非你真的只想计算左侧节点。
相关文章:
- 反向给定链表中的K节点
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- Boost Graph Library,修复节点大小
- C++A*算法并不总是在路径中具有目标节点
- 如何找到2个单链表的公共节点
- 在C++中使用GDAL可以将图像的像素坐标转换为lat,long吗
- 计算每个节点的树高,帮助我解释这个代码解决方案
- UE4-如何在给定4个屏幕坐标的情况下缩放纹理或材质
- 为什么我的删除节点函数实际上没有删除节点?
- 我们可以删除链表中静态内存中的节点吗
- 如何在pugixml中获取节点的内部XML
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 节点 *temp; 和节点 *tmp = 新节点之间的差异
- 比较两个节点坐标的最佳方法是什么?
- 柠檬图库C++节点中添加坐标
- 二进制搜索树计算节点的坐标