Implement an algorithm for inserting an element into a binary tree java

Ideas

Because the given binary tree is a binary tree, you can insert an element at any place. For insertion, you can use the method of traversal in order to find a node whose left child or right child node is empty, and then insert the element

void insertInBinaryTree(BinaryTreeNode root,int data){
    
    
  LLQueue q = new LLQueue();
  BinaryTreeNode temp;
  BinaryTreeNode newNode = new BinaryTreeNode();
  newNode.setData(data);
  if(root == null){
    
    
    root = newNode;
    return;
  }
  q.enqueue(root);
  while(q.isNotEmpty()){
    
    
     temp = q.dequeue();
     if(temp.getLeft() != null){
    
    
       q.enqueue(temp.getLeft());
     }else{
    
    
       temp.setLeft(newNode);
       q.deleteQueue();
       return;
     }
     if(temp.getRight()!=null){
    
    
       q.enqueue(temp.getRight());
     }else{
    
    
       temp.setRight(newNode);
       q.deleteQueue();
       return;
     }
  }
  q.deleteQueue();
}

Guess you like

Origin blog.csdn.net/weixin_37632716/article/details/110142081