Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //params: key of node to be inserted, parent node
- public void insert(int newKey, TreeNode parent){
- //if the root of the tree is empty, insert at root
- if(this.getRoot() == null){
- this.root = new TreeNode(newKey, null, null);
- }
- //if the node is null, insert at this node
- else if(parent == null)
- parent = new TreeNode(newKey, null, null);
- else{
- //if the value is less than the value of the current node, call insert on the node's left child
- if(newKey < parent.getKey()) {
- insert(newKey, parent.getLeft());
- }
- //greater than value of current node, call insert on node's right child
- else if(newKey > parent.getKey()){
- insert(newKey, parent.getRight());
- }
- //same as value of current node, increment iteration field by one
- else if(newKey == parent.getKey())
- parent.incrementIterations();
- }
- }
- public Node insertNode(Node head, int data) {
- if(head == null){
- head = new Node();
- head.data = data;
- return head;
- }
- if(head.data < data) {
- head.right = insertNode(head.right,data);
- } else {
- head.left = insertNode(head.left, data);
- }
- return head;
- }
Add Comment
Please, Sign In to add comment