[英]Return pointer to nth node in level-ordered binary tree
假設我按級別順序有這個二叉樹:
我想返回一個指向第5個節點的指針。 我在構造函數時遇到了麻煩。
這是我到目前為止的內容:
Node* GetNodeAtCount(Node *r, int x)
{
if(r != NULL)
{
if(r->count == x) {return r;}
else
{
GetNodeAtCount(r->left, x); // my problem is here
GetNodeAtCount(r->right, x);
}
}
}
我的函數只能正確返回樹的右側。 我無法找出一種方法來分別調用遞歸函數,因為我無法通過比較“大於”或“小於”來進行過濾,即轉到右子樹,左子樹等。
我不熟悉C ++,因此這將是偽代碼:
If the current node does not exists:
return failure
If (the node is the one you are after):
return the current node
result=recurse(left node)
if result != failure:
return result
return recurse(right node) // which may be failure
編輯后,在開始時添加“當前節點不存在”的檢查; 這簡化了其余的代碼。 我認為在C ++中,您將其與null對象進行比較?
如果您的樹是按計數排序的,則可以從此處進行比較和分支:
else if (x < r->count && r->left != NULL) { return GetNodeAtCount(r->left, x); }
else if (x > r->count && r->right != NULL) { return GetNodeAtCount(r->right, x); }
else { return NULL; }
不要忘記檢查r-> left和r-> right的NULL值! 注意這些行中的返回調用。
如果您的樹未按計數排序,則必須檢查返回值。
else
{
Node *ret;
ret = (r->left != null ? GetNodeAtCount(r->left, x) : NULL);
ret = (ret == NULL && r->right != null ? GetNodeAtCount(r->right, x) : ret);
return ret;
}
但是,如果使用的樹沒有排序,則應重新考慮數據結構,並可能使用更合適的方法。 甚至向量/數組也將比搜索未排序的樹更快。 如果由於要對其他字段進行排序而使用樹,則考慮使用B +樹。
您需要遞歸地調用左側的樹,也許這樣會起作用-
Node* GetNodeAtCount(Node *r, int x)
{
if(r != NULL)
{
if(r->count == x) {return r;}
Node *temp = GetNodeAtCount(r->right, x); //check right tree for match
if (temp != NULL)
return temp;
return GetNodeAtCount(r->left, x); // if right tree does not match further go into left tree
}
return NULL //return NULL if it is the end of tree so that the check temp != NULL will work correctly
}
讓我知道這是否對您有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.