[英]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);
除非您真的只想計算左側節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.