[JAVA] detailed explanation of data insertion algorithm of binary tree

Posted by Avi on Sun, 19 Dec 2021 02:19:01 +0100

Example:
leetcode question 701
Binary tree insert data
Title:
Given the root node of the binary search tree (BST) and the value to be inserted into the tree, insert the value into the binary search tree. Returns the root node of the inserted binary search tree. The input data ensures that the new value is different from any node value in the original binary search tree.

There are three ways to traverse a binary tree
Preorder traversal: the left and right order of the root
Middle order traversal: left root right order
Post order traversal: the order of left and right roots
What is the principle / idea of inserting data into binary tree?
The number on the left side of the binary tree will be smaller than the number on the right side, so we compare the size of the data to be inserted with the value of the root node. If the inserted data is larger than the root node, the root node will be transferred to the node on the right. At this time, repeat the above operation to complete the insertion.

Let's read the TreeNode code snippet:

class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
}

Obviously, binary trees are linked through left and right, which is very similar to the next of ListNode, except that binary trees are two-way links and linked lists are one-way links. So we need to get the parent node and link the number of inserts with the parent node's left or right.

So how can we get the node that can insert the data correctly?
1. We can obtain the last non empty node by looping mobile nodes

 //Define a parent binary tree to record the nodes of the last operation
        TreeNode parent =root,cur=root;
        while(cur!=null){
            //If the p part is empty, compare it with val to move the node
            parent = cur; //Record the previous node for the last link
            cur = cur.val<val?cur.right:cur.left;//Node to move.
        }

2. Then compare the value of the last non empty node with the insertion value, and insert the small one on the left and the large one on the right.
code implementation

if(parent.val>val){
            //If the parent's val is greater than the entered val, insert it on the left
            parent.left = new TreeNode(val);
        }else{
            //Otherwise, insert it on the right
            parent.right = new TreeNode(val);
        }

Overall code

 if (root == null){
            return new TreeNode(val);
        }
        //Define a parent binary tree to record the nodes of the last operation
        TreeNode parent =root,cur=root;
        while(cur!=null){
            //If the p part is empty, compare it with val to move the node
            parent = cur; //Record the previous node for the last link
            cur = cur.val<val?cur.right:cur.left;//Node to move.
        }
        if(parent.val>val){
            //If the parent's val is greater than the entered val, insert it on the left
            parent.left = new TreeNode(val);
        }else{
            //Otherwise, insert it on the right
            parent.right = new TreeNode(val);
        }
        return root;

Of course, because the movement of nodes keeps repeating an operation, we can use a simpler recursive implementation

 public TreeNode insertIntoBST(TreeNode root, int val) {
          if (root == null){
            return new TreeNode(val);
          }
          if(root.val<val){
              //Because the value of the parent node is less than the insertion value, move the node to the right
              root.right = insertIntoBST(root.right,val);
          }else{
              root.left = insertIntoBST(root.left,val);
          }
        return root;
    }

Overall code

package JAVA algorithm.LeetCode;

public class t701 {
    /**
    701. Insert operation in binary search tree
    Binary tree is divided into pre order insertion, middle order insertion and post order insertion
    Solution 1 The insertion of binary tree is realized by using iterative idea
     */

}


class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
}

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */


class Solution {
    /*
        Binary tree insertion principle:
        1.Pre order insertion (left and right roots): if the number of inserted trees is greater than the number of roots, move to the right, compare with the roots of the branches on the right, and then repeat the previous operation
        */
    public TreeNode insertIntoBST(TreeNode root, int val) {
        //When the incoming root node is empty, the incoming value is set to node
        if (root == null){
            //If the tree is empty, a new binary is created and assigned
            return new TreeNode(val);
        }

        if (root.val<val){
            //When the current value is greater than the value on the left, it moves to the right
            root.right=insertIntoBST(root.right,val);
        }else{
            //conversely
            root.left=insertIntoBST(root.left,val);
        }
        return root;
    }


    //Solution 2: Circular judgment
    public TreeNode insertIntoBST2(TreeNode root, int val) {
        if (root == null){
            return new TreeNode(val);
        }
        TreeNode parent=root,p=root;
        while(true){
            if (p!=null){
                parent = p; //Record last node
                p = p.val>val?p.left:p.right;
            }else{
                //When p is null, the location has been found, and now you need to insert the value
                if (parent.val>val){
                    parent.left = new TreeNode(val);
                }else{
                    parent.right = new TreeNode(val);
                }
                break;
            }

        }
        return root;
    }
    //Solution 3: loop traversal,

    /**
     *
     * @param root
     * @param val
     * @return
     *
     * Solution idea: we first find the parent node that can be inserted through a loop,
     * Then we compare the value with the value of the parent node. If the value is less than the parent node, we insert it to the left of the parent node
     */
    public TreeNode insertBST3(TreeNode root,int val){
        if (root == null){
            return new TreeNode(val);
        }
        //Define a parent binary tree to record the nodes of the last operation
        TreeNode parent =root,p=root;
        while(p!=null){
            //If the p part is empty, compare it with val to move the node
            parent = p; //Record the previous node for the last link
            p = p.val<val?p.right:p.left;//Node to move.
        }
        if(parent.val>val){
            //If the parent's val is greater than the entered val, insert it on the left
            parent.left = new TreeNode(val);
        }else{
            //Otherwise, insert it on the right
            parent.right = new TreeNode(val);
        }

        return root;
    }


}


Topics: Java Algorithm leetcode Binary tree