public class TreeNode{ public TreeNode left, right, parent; public Comparable data; public TreeNode() { this(null, null, null); } public TreeNode(TreeNode l, TreeNode r, Comparable o) { this.left = l; this.right = r; this.data = o; parent = null; } public void setLeft(TreeNode l) { left = l; } public TreeNode getLeft() { return left; } public void setRight(TreeNode r) { right = r; } public TreeNode getRight() { return right; } public void setParent(TreeNode p) { parent = p; } public TreeNode getParent() { return parent; } public void setDate(Comparable o) { data = o; } public Comparable getData() { return data; } /*public String toString() { String leftstring, rightstring, datastring; /* Zeiger auf den linken Knoten if (left != null) leftstring = "" + left.getData(); else leftstring = "-"; /* Zeiger auf den rechten Knoten if (right != null) rightstring = "" + right.getData(); else rightstring = "-"; /* Nutzdaten if (getData() != null) datastring = "" + getData(); else datastring = "-"; /* Rückgabe return "[" + leftstring + "|" + datastring + "|" + rightstring + "]"; }*/ }
public class TreeNodeTest{ public static void main(String[] args) { Integer zwei = new Integer(2); Integer drei = new Integer(3); Integer vier = new Integer(4); Integer fuenf = new Integer(5); Integer sieben = new Integer(7); Integer acht = new Integer(8); einfuegen binaerenBaum = new einfuegen(); binaerenBaum.insert(zwei); binaerenBaum.insert(drei); System.out.println(binaerenBaum); }}
public class einfuegen{ public TreeNode root; public einfuegen() { TreeNode root = new TreeNode(); } void insert(Comparable o) { TreeNode x = new TreeNode(null, null, o); if (root==null) root = x; else insert(root,x); } /* Hilfmethode zum Einfügen eines Knotens in den Baum */ void insert(TreeNode unterbaum, TreeNode x) { if (x.getData().compareTo(unterbaum.getData())<0) { TreeNode links = unterbaum.getLeft(); if (links==null) { unterbaum.setLeft(x); x.setParent(unterbaum); // Parent setzen } else insert(links, x); } else if (x.getData().compareTo(unterbaum.getData())>0) { TreeNode rechts = unterbaum.getRight(); if (rechts==null) { unterbaum.setRight(x); x.setParent(unterbaum); // Parent setzen } else insert(rechts, x); } } public String inorder() { if (root!=null) return inorder(root); else return ""; } public String inorder(TreeNode k) { String rueckgabe = ""; if (k.getLeft() != null) rueckgabe = rueckgabe + inorder(k.getLeft()); rueckgabe = rueckgabe + k.getElement() + " "; if (k.getRight() != null) rueckgabe = rueckgabe + inorder(k.getRight()); return rueckgabe; }}