[英]Constructing full binary tree given only postorder?
我正在嘗試構造一個完整的二叉樹(完全意味着每個非葉節點都有兩個與其連接的葉節點,即node->right
和node->left
為!= NULL
),僅給出了樹的后序遍歷。 另外,還給出了后遍歷中的節點是否為葉節點。 給定的后序遍歷如下所示:
2(1.000000e+00)
3(1.000000e+00)
(1.000000e+00 1.000000e+00)
1(1.000000e+00)
(1.000000e+00 2.000000e+00)
例如,格式為"%d(%le)"
的一行是葉節點,而"(%le %le)"
是一個非葉節點。 通常,您不能僅使用后序來構造樹,因為存在多種連接可能性,但是我敢肯定,區分葉子節點和非葉子節點在某種程度上很重要。 我當前的函數如下所示:
Node *constructTreeHelper(FILE *infile, int *index) {
// Base case
if (*index <= 0) {
return NULL;
}
Node *root = NULL;
// Check for the "(" character
int check;
check = getc(infile);
fseek(infile, -1, SEEK_CUR);
// If the node is not a leaf node
if (check == 40) {
double lwire, rwire;
fscanf(infile, "(%le %le)\n", &lwire, &rwire);
root = createNode(0, 0, lwire, rwire);
*index = *index - 1;
if (*index >= 0) {
root->right = constructTreeHelper(infile, index);
root->left = constructTreeHelper(infile, index);
}
} else {
// If the node is a leaf node
int sink;
double cap;
fscanf(infile, "%d(%le)\n", &sink, &cap);
root = createNode(sink, cap, 0, 0);
*index = *index - 1;
if (*index >= 0) {
root->right = constructTreeHelper(infile, index);
root->left = constructTreeHelper(infile, index);
}
}
return root;
}
其中index
等於樹中的節點數-1。顯然,此實現僅在右側構建節點。 如何更新它以正確構造樹?
編輯:讓我添加一些有關我所知道的更多信息。 因此,第一個節點始終必須是葉節點,而最后一個節點始終必須是根節點。 由於這不是二進制搜索樹,而是簡單的二進制樹,因此您不能每次使用更新的范圍參數來遞歸調用該函數。 我的實現應在O(n)時間內解決它,但我只是想不通如何在構造樹時利用節點是否為葉節點的知識。
您的代碼中存在一些問題:
您應該使用ungetc()
而不是fseek()
來回溯一個字符,以避免在不支持查找的流上失敗。
您應該編寫(check == '(')
而不是對ASCII字符值進行硬編碼。它既可移植,也更具可讀性。
為避免未定義的行為,應檢查EOF
和fscanf()
解析是否成功。 實際上,這將避免對check
進行測試的需要。
解析葉節點時,不應遞歸並解析當前節點以下的其他節點。
index
似乎是多余的,因為節點的順序應該足以完全確定在哪里停止。
這是修改后的版本:
Node *constructTreeHelper(FILE *infile, int *index) {
double lwire, rwire;
int sink;
double cap;
Node *node;
// Base case
if (*index <= 0) {
// This test seems redundant with the file contents */
return NULL;
}
// this fscanf will fail on the byte byte if it is not a '('
if (fscanf(infile, " (%le %le)", &lwire, &rwire) == 2) {
// If the node is not a leaf node
node = createNode(0, 0, lwire, rwire);
*index -= 1;
node->right = constructTreeHelper(infile, index);
node->left = constructTreeHelper(infile, index);
} else if (fscanf(infile, "%d(%le)\n", &sink, &cap) == 2) {
// If the node is a leaf node
node = createNode(sink, cap, 0, 0);
*index -= 1;
} else {
// invalid format or end of file */
node = NULL;
}
return node;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.