This method is part of the Binary Search Tree implementation. Question: Replace
ID: 3729521 • Letter: T
Question
This method is part of the Binary Search Tree implementation. Question: Replace the put(K key, V value) method with a recursive method – i.e. one that doesn’t use a loop. public void put(K key, V value) { if (root == null) { TreeNode node = new TreeNode(key, value); this.root = node; } else { TreeNode current = root; while (current != null) { int c = key.compareTo(current.key); // key == current.key if (c == 0) { current.value = value; return; } // key < current.key else if (c < 0) { if (current.left != null) { current = current.left; } else { TreeNode node = new TreeNode(key, value); current.left = node; } } //c > 0, i.e. key > current.key else { if (current.right != null) { current = current.right; } else { TreeNode node = new TreeNode(key, value); current.right = node; } } } } }
Explanation / Answer
public Node put(Node temp, K key, V value) { if(temp == null) { return new TreeNode(key, value); } else if(key.compareTo(temp.key) < 0) { temp.left = put(temp.left, key, value); return temp; } else { temp.right = put(temp.right, key, value); return temp; } } public void put(K key, V value) { this.root = put(this.root, key, value); }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.