Simple Binary Tree in Java in just one class -
i have implement simple binary tree. need put
, get
method. if key in use have replace value. code i'm very unsure if working right... can confirm code work? sorry... don't know how debug such class... :/ , no - not homework. template course learn java... ;)
//don't import other classes. public class binarytree<k extends comparable<k>, v> { //please don't add further attributes. private k key; private v value; private binarytree<k, v> left; private binarytree<k, v> right; /** * class binary tree-based collection key-value-pairs. */ public static void main(string[] args) { binarytree<integer, string> treeinteger = new binarytree<>(2, "two "); treeinteger.put(1, "one "); treeinteger.put(0, "zero "); treeinteger.put(3, "three "); treeinteger.put(6, "six "); treeinteger.put(3, "threenew "); system.out.println(tree.tostring()); if (tree.get(4) == null) { system.out.println("null"); } } public binarytree(k key, v value) { //fill in solution here. this.key = key; this.value = value; } public void put(k key, v value) { //fill in solution here. if (this.key.compareto(key) > 0 ) { // links if (this.left == null) { this.left = new binarytree<>(key, value); } else { left.put(key, value); } } else if (this.key.compareto(key) < 0) { if (this.right == null) { this.right = new binarytree<>(key, value); } else { this.right.put(key, value); } } else if (this.key.compareto(key) == 0) { this.key = key; this.value = value; } } public v get(k key) { //fill in solution here. if (this.key.compareto(key) > 0 && this.left != null) { return this.left.get(key); } else if (this.key.compareto(key) < 0 && this.right != null) { return this.right.get(key); } else if (this.key.compareto(key) == 0 && this.value != null) { return this.value; } else if (this.key == key) { return value; } return null; } }
my own touring
string s = ""; if (left != null) { s += left.tostring(); } if (value != null) { s += value.tostring(); } if (right != null) { s += right.tostring(); } return s;
add , test:
@override public string tostring() { if(this.left==null&&this.right != null){ return this.value.tostring()+" " + this.right.tostring(); } if(this.left!=null&&this.right == null){ return this.value.tostring()+" " + this.left.tostring(); } if(this.left !=null && this.right != null) return this.value.tostring()+" " + this.left.tostring() +" " + this.right.tostring(); return this.value.tostring();; }
this preorder tree traversal prints nodes in tree. if create tree correctly, should able print values.
to print in ascending order, use in-order tree traversal:
@override public string tostring() { if(this.left==null&&this.right != null){ return this.value.tostring()+" " + this.right.tostring(); } if(this.left!=null&&this.right == null){ return this.left.tostring() +" " + this.value.tostring(); } if(this.left !=null && this.right != null) return this.left.tostring() +" " +this.value.tostring()+" " + this.right.tostring(); return this.value.tostring(); }