Skip to content

Instantly share code, notes, and snippets.

@fcamel
Created August 8, 2011 03:16
Show Gist options
  • Save fcamel/1131149 to your computer and use it in GitHub Desktop.
Save fcamel/1131149 to your computer and use it in GitHub Desktop.
if-else style comparison
// #1
void add_node(Node *node, Node *new_node) {
if (new_node->value <= node->value) {
if (node->left == NULL) {
node->left = new_node;
return;
}
add_node(node->left, new_node);
return;
}
if (node->right == NULL) {
node->right = new_node;
return;
}
add_node(node->right, new_node);
}
// #2
void add_node(Node *node, Node *new_node) {
if (new_node->value <= node->value) {
if (node->left == NULL) {
node->left = new_node;
} else {
add_node(node->left, new_node);
}
} else {
if (node->right == NULL) {
node->right = new_node;
} else {
add_node(node->right, new_node);
}
}
}
@hotoo
Copy link

hotoo commented Aug 8, 2011

比较喜欢第1种,不过有时候不能 return,只能使用第2种了。

@fcamel
Copy link
Author

fcamel commented Aug 8, 2011

遇到不方便 return 時, 我通常會將那段 code 抽成一個小函式, 這樣就能用 return 了

@hotoo
Copy link

hotoo commented Aug 8, 2011

// #3
void add_node(Node *node, Node *new_node) {
    if (new_node->value <= node->value) {
        if (node->left == NULL) {
            node->left = new_node;
        } else {
            add_node(node->left, new_node);
        }
    } else {
        if (node->right == NULL) {
            node->right = new_node;
        } else {
            add_node(node->right, new_node);
        }
    }
    // run the code anyway.
    // how to early return with sub-function?
}

@fcamel
Copy link
Author

fcamel commented Aug 8, 2011

void _add_node(Node *node, Node *new_node); // this is exactly the same as the old add_node()

void add_node(Node *node, Node *new_node) {
     _add_node(node, new_node);
    // the following codes can return as you wish.
}

@todykuo
Copy link

todykuo commented Aug 8, 2011

不用 recursive 的寫法
不知道這樣寫有沒有錯 @@"

// #3
Node *root_node;
void add_node( Node *new_node )
{
    Node **pnode = &root_node;
    while( (*pnode) != NULL ) {
        if( new_node->value <= (*pnode)->value )
            pnode = &((*pnode)->left);
        else
            pnode = &((*pnode)->right);
    }
    (*pnode) = new_node;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment