Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Tree1 {
- class Node {
- private int elem;
- private Node left;
- private Node right;
- public Node(int elem) {
- this.elem = elem;
- }
- public void add(int el) {
- if (el < this.elem) {
- if (this.left == null) {
- this.left = new Node(el);
- } else {
- this.left.add(el);
- }
- } else if (el >= this.elem) {
- if (this.right == null) {
- this.right = new Node(el);
- } else {
- this.right.add(el);
- }
- }
- }
- Node copyTree() {
- // TODO: Implementieren Sie die Methode
- //TODO: Diese Zeile löschen oder entsprechend verändern.
- Node copy = new Node(elem);
- if (this.left != null) {
- copy.left = this.left.copyTree();
- }
- if (this.right != null) {
- copy.right = this.right.copyTree();
- }
- return copy;
- }
- public String toString() {
- return (this.left == null ? "" : this.left.toString() + ",")
- + this.elem + (this.right == null ? "" : "," + this.right.toString());
- }
- }
- private Node root;
- public void add(int elem) {
- if (this.root == null) {
- this.root = new Node(elem);
- } else {
- this.root.add(elem);
- }
- }
- // Diese Methode kopiert den vorhandenen Baum und erstellt eine exakte
- // Kopie. Dafür sollen keine zusätzliche Datenstrukturen verwendet werden.
- // Es wird der Wurzelknoten des kopierten Baumes zurückgegeben.
- public Node copyTree() {
- if (this.root == null) {
- return null;
- }
- return this.root.copyTree();
- }
- public String toString() {
- return this.root == null ? "()" : this.root + "";
- }
- public static void main(String[] args) {
- Tree1 tree = new Tree1();
- tree.add(10);
- tree.add(12);
- tree.add(11);
- tree.add(5);
- tree.add(1);
- tree.add(6);
- tree.add(14);
- System.out.println(tree);
- Node copy = tree.copyTree();
- System.out.println(copy);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement