Question: I came across some threads on StackOverflow but none of them quite cleared my doubts.

So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.

```
BST newNode(int x)
{
    BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
    node->Element = x;
    node->Left = NULL;
    node->Right = NULL;

    return node;

}

BST Insert(int x, BST T)
{
    BST temp_node = T;
    while( T != NULL)   {
        if (x < T->Element)
            T = T->Left;
        else if (x >= T->Element)
            T = T->Right;
    }

    T = newNode(x);

    return temp_node;

}

```

However, when I'm finding the height of this tree I am always getting 0. The height code is

```
int Height(BST T)
{
    if (T == NULL)
        return 0;

    return 1+(max(Height(T->Left), Height(T->Right)));
}

```

and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)

What am I missing?

Answer: 
Here's My implementation of the aforementioned problem:

```
bst* newNode(int x)
{
    bst* T = new bst;
    T->value = x;
    T->left_child = T->right_child = NULL;
    return T;
}

bst* bst_insert_iter(bst* T,int val)
{
    if (T == NULL)
        T = newNode(val);

    else
    {

    bst *temp_node = T;

    bool flag = true;

    while(flag)   
    {
        if (val <= temp_node->value)
        {
            if (temp_node->left_child == NULL)
            {
                temp_node->left_child=newNode(val);
                flag = false;
            }
            else
                temp_node = temp_node->left_child;
        }

        else
        {
            if (temp_node->right_child == NULL)
            {
                temp_node->right_child=newNode(val);
                flag = false;
            }
            else
                temp_node = temp_node->right_child;
        }
    }

    }
    return T;
}

```
Here is my version , it seems to be working. 

```
struct tree{
tree *left;
tree *right;
int key;
};
void insertBst(int k,tree *t)
{
    tree *newK = new tree[sizeof(tree)];
    newK->key = k;
    newK->left = NULL;
    newK->right = NULL;
    if((t)->key == NULL)
    {
        t=newK;
        return;
    }
    else{
        bool found = false;
        tree *root = t;
        tree *parent = NULL;
        while(root != NULL)
        {
        parent = root;
            if(root->key < newK->key)
            {
                root=root->right;
            }
            else if(root->key > newK->key)
            {
                root=root->left;
            }
            else{
            //Here we have duplicates!! so do nothing
            root = root;
            }
        }
        if(parent->key > newK->key) parent->left = newK;
        else parent->right = newK;  
    }   

}

```