Non-recursive add function in a binary tree using c++

断了今生、忘了曾经 提交于 2019-12-06 14:46:03

You are not adding the new node to the tree, just running down the tree and filling parent with a new node, but never adding it to the tree, change below code:

parent = new treeNode;
parent->data=num;
parent->left=NULL;
parent->right=NULL;
temp=parent;

To:

treeNode *newNode = new treeNode;
newNode->data = num;
newNode->left = NULL;
newNode->right = NULL;

//Now insert the new node BELOW parent
if(num <= parent->data)
    parent->left = newNode;
else
    parent->right = newNode;

The problem might be that you never add your new node to the tree.

  parent = new treeNode;
  parent->data=num;
  parent->left=NULL;
  parent->right=NULL;
  temp=parent;

You assign your new node to temp and parent, which are temporary variables and therefore don't exist outside of the function. What you have to do is assign your new node to either parent->left or parent->right, depending on which side your new input lies, in order to link it into the the tree. Therefore what you want to do is something like the following:

  temp = new treeNode;
  temp->data=num;
  temp->left=NULL;
  temp->right=NULL;
  if(num < parent->data)
     parent->left = temp;
  else
     parent->right = temp;
Tejas Rawat

Algo

  1. if root == null Create new node assign to Root
  2. Keep iterating based on comparison with rootNode until reach any leaf Node
  3. check if num <= parent(leaf) Insert into left ELSE insert into right

Code

private void insertItrInBST(int num){
    Node temp = root,parent = root;

    if(root == null){
        root = getNewNode(num);
    }else{
        temp = root;

        while(temp != null){
            if(num <= root.data){
                parent = temp;
                temp = temp.left;   
            }else{
                parent = temp;
                temp = temp.right;
            }
        }
        Node newNode = getNewNode(num);
        if(num <= parent.data){
            parent.left = newNode;
        }else{
            parent.right = newNode;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!