0

Im working on a C library for binary tree, and Im wondering how I could save the value of the root of the tree to be able to display it later in a function.

My tree struct:

struct Node {
    int value;
    struct Node *left;
    struct Node *right;
};

typedef struct Node TNode;
typedef struct Node *binary_tree;

The binary tree root is initialised with the 3 value like this:

caller:

tree = NewBinaryTree(3);

NewBinaryTree method:

binary_tree NewBinaryTree(int value_root) {
    binary_tree newRoot = malloc(sizeof(TNode));
    if (newRoot) {
        newRoot->value = value_root;
        newRoot->left = NULL;
        newRoot->right = NULL;
    }
    return newRoot;
}

Basically I would like to be able to do a function that just display the value_root function even after adding elements to the binary tree and be able to still display the value_root value.This might be very basic but im learning C and im not sure.

thank you

  • I'm not sure if I understood the question corretly; would it be an option to save the return value of `NewBinaryTree` somewhere else to refer to it later? – Codor Dec 08 '16 at 19:36
  • 3
    In the caller: `printf( "%d\n", tree->value )` – user3386109 Dec 08 '16 at 19:37
  • I am unclear what you are asking, but perhaps `if(tree) printf("left=%p data=%d right=%p\n", (void*)tree->left, tree->value, (void*)tree->right);` – Weather Vane Dec 08 '16 at 19:38
  • @Codor Yes well just the value of the "root" of the binary tree(3 in this case).Because afterwards I add element to the binary tree and I want to be able to just display the root (3 value) later on – Christopher M. Dec 08 '16 at 19:38
  • 1
    @user3386109 Exactly! thank you! – Christopher M. Dec 08 '16 at 19:41
  • 2
    See: [Is it a good idea to typedef pointers](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) — succinctly, the answer is No. – Jonathan Leffler Dec 08 '16 at 20:01

1 Answers1

0

In the caller: printf( "%d\n", tree->value ) – user3386109

Armali
  • 18,255
  • 14
  • 57
  • 171