Constructing full binary tree given only postorder?

本秂侑毒 提交于 2019-12-02 00:46:01

There are some problems in your code:

  • you should use ungetc() instead of fseek() to backtrack by one character to avoid failure on streams that do not support seeking.

  • you should write (check == '(') instead of hard coding the ASCII character value. It is both more portable and more readable.

  • To avoid undefined behavior, you should check for EOF and for fscanf() parsing success. As a matter of fact, this would avoid the need for the test on check.

  • When you parse a leaf node, you should not recurse and parse further nodes below the current one.

  • index seems redundant as the sequence of nodes should suffice to full determine where to stop.

Here is a modified version:

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;
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!