Equals method in two Trees [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Guys i created two trees. I wrote a method but it does not work correctly.
My method does not work recursively and prints only "false".
In general, I need to recurse through the elements of a tree, and If two trees are similar, then it should output - "true". If two rees not similar, then it should output - false. Please help me write code eqauls method in my trees
My code:
public class TreePrint {
public static void main(String[] args) {
Tree<String> rootFolder = new Tree<>("RootFolder");
Node<String> video = rootFolder.addChild("Video");
Node<String> music = rootFolder.addChild("Music");
Node<String> picture = rootFolder.addChild("Picture");
video.addChild("Terminator");
video.addChild("Die Hard");
video.addChild("Rocky");
music.addChild("Eminem");
Node<String> picture01 = picture.addChild("Picasso");
picture01.addChild("Do Vinci");
Node<String> picture02 = picture01.addChild("NN");
picture02.addChild("Cartoon");
picture02.addChild("Comics");
Tree2<String> rootFolder1 = new Tree2<>("RootFolder");
printTree(rootFolder);
printTree(rootFolder1);
boolean b1 = rootFolder.contains("P0");
//System.out.println(b1);
boolean b2 = rootFolder1.contains("Eminem");
//System.out.println(b2);
System.out.println(rootFolder.equals(rootFolder1));
}
private static <T> void printTree(Node<T> node) {
printTree(node, 0);
}
private static <T> void printTree(Node<T> node, int level) {
printNode(node, level);
if (node.getChildren() != null) {
for (Node childNode : node.getChildren()) {
printTree(childNode, level + 1);
}
}
}
private static <T> void printNode(Node<T> kid, int level) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(kid.getData());
}
}
public class Tree<T> extends Node<T> {
public Tree(T data) {
super(data, null);
}
public boolean contains(T value) {
return recurse(iterate(), value);
}
private boolean recurse(List<Node<T>> children, T value) {
return children.stream()
.anyMatch(item -> item.getData().equals(value) || item.iterate().size() > 0 && recurse(item.iterate(), value));
}
public boolean equals(Object obj) {
return isEquals(obj);
}
private boolean isEquals(Object obj
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Node other = (Node) obj;
if (children == null) {
if (other.children != null) {
return false;
}
} else if (!children.equals(other.children)) {
return false;
}
if (data == null) {
if (other.data != null) {
return false;
}
} else if (!data.equals(other.data)) {
return false;
}
return true;
}
}
public class Node<T> {
private T data;
private final List<Node<T>> children = new ArrayList<>();
private final Node<T> parent;
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
public void addChild(Node<T> node) {
children.add(node);
}
public Node<T> addChild(T nodeData) {
Node<T> newNode = new Node<T>(nodeData, this);
children.add(newNode);
return newNode;
}
public List<Node<T>> iterate() {
return children;
}
public void remove(Node<T> node) {
children.remove(node);
}
public List<Node<T>> getChildren() {
return children;
}
public Node getParent() {
return parent;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
public class Tree2<T> extends Node<T> {
public Tree2(T data) {
super(data, null);
}
public boolean contains(T value) {
return recurse(iterate(), value);
}
private boolean recurse(List<Node<T>> children, T value) {
return children.stream()
.anyMatch(item -> item.getData().equals(value) || item.iterate().size() > 0 && recurse(item.iterate(), value));
}
}

The problem is is this line
if (getClass() != obj.getClass()) {
return false;
}
As one object is of class Tree and other is of Tree2

I have no idea why do you need two classes Tree and Tree2 but:
TreePoint
public class TreePoint {
public static void main(String[] args) {
Tree<String> rootFolder = new Tree<>("RootFolder");
Node<String> video = rootFolder.addChild("Video");
Node<String> music = rootFolder.addChild("Music");
Node<String> picture = rootFolder.addChild("Picture");
video.addChild("Terminator");
video.addChild("Die Hard");
video.addChild("Rocky");
music.addChild("Eminem");
Node<String> picture01 = picture.addChild("Picasso");
picture01.addChild("Do Vinci");
Node<String> picture02 = picture01.addChild("NN");
picture02.addChild("Cartoon");
picture02.addChild("Comics");
Tree2<String> rootFolder1 = new Tree2<>("RootFolder");
Node<String> video1 = rootFolder1.addChild("Video");
Node<String> music1 = rootFolder1.addChild("Music");
Node<String> picture1 = rootFolder1.addChild("Picture");
video1.addChild("Terminator");
video1.addChild("Die Hard");
video1.addChild("Rocky");
music1.addChild("Eminem");
Node<String> picture011 = picture1.addChild("Picasso");
picture011.addChild("Do Vinci");
Node<String> picture021 = picture011.addChild("NN");
picture021.addChild("Cartoon");
picture021.addChild("Comics");
printTree(rootFolder);
printTree(rootFolder1);
System.out.println(rootFolder.equals(rootFolder1));
}
private static <T> void printTree(Node<T> node) {
printTree(node, 0);
}
private static <T> void printTree(Node<T> node, int level) {
printNode(node, level);
if (node.getChildren() != null) {
for (Node childNode : node.getChildren()) {
printTree(childNode, level + 1);
}
}
}
private static <T> void printNode(Node<T> kid, int level) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(kid.getData());
}
}
Tree
import java.util.List;
public class Tree<T> extends Node<T> {
public Tree(T data) {
super(data, null);
}
public boolean contains(T value) {
return recurse(iterate(), value);
}
private boolean recurse(List<Node<T>> children, T value) {
return children.stream()
.anyMatch(item -> item.getData().equals(value) || item.iterate().size() > 0 && recurse(item.iterate(), value));
}
}
Node
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Node<T> {
public T data;
public final List<Node<T>> children = new ArrayList<>();
public final Node<T> parent;
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
public void addChild(Node<T> node) {
children.add(node);
}
public Node<T> addChild(T nodeData) {
Node<T> newNode = new Node<T>(nodeData, this);
children.add(newNode);
return newNode;
}
public List<Node<T>> iterate() {
return children;
}
public void remove(Node<T> node) {
children.remove(node);
}
public List<Node<T>> getChildren() {
return children;
}
public Node getParent() {
return parent;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
Node<?> node = (Node<?>) o;
return Objects.equals(data, node.data) &&
Objects.equals(children, node.children);
}
#Override
public int hashCode() {
return Objects.hash(data, children, parent);
}
}
Tree2
import java.util.List;
public class Tree2<T> extends Node<T> {
public Tree2(T data) {
super(data, null);
}
public boolean contains(T value) {
return recurse(iterate(), value);
}
private boolean recurse(List<Node<T>> children, T value) {
return children.stream()
.anyMatch(item -> item.getData().equals(value) || item.iterate().size() > 0 && recurse(item.iterate(), value));
}
}

Related

Inserting an integer into a regular binary tree

While revising for my final, I came across binary trees (regular ones). After going through the lecture, I started to solve previous labs.
My problem here is that only 6 is inserted into the tree. What is wrong with my method?
What I'm trying to input:
tree.insert(1); tree.insert(15); tree.insert(7);
tree.insert(13); tree.insert(58); tree.insert(6);
The Node class:
public class Node {
public int key;
public Node left_child;
public Node right_child;
// The Constructor(s).
public Node() {
}
public Node(int key) {
this.key = key;
left_child = null;
right_child = null;
}
// The Get Methods.
public int getKey() {
return key;
}
public Node getLeft_child() {
return left_child;
}
public Node getRight_child() {
return right_child;
}
// The Set Methods.
public void setKey(int key) {
this.key = key;
}
public void setLeft_child(Node left_child) {
this.left_child = left_child;
}
public void setRight_child(Node right_child) {
this.right_child = right_child;
}
}
The BinaryTree class:
public class BinaryTree {
private Node root;
// The Constructor Method(s)
public BinaryTree() {
root = null;
}
public boolean is_empty() {
return (root == null);
}
public void insert(int k) {
insert(root, k);
}
private Node insert(Node x, int k) {
Node p = new Node(k);
if (x == null) {
root = p;
}
else {
if (x.left_child != null) {
insert(x.left_child, k);
}
else {
insert(x.right_child, k);
}
}
return x;
}
// Printing Method(s).
public void print_inorder() {
print_inorder(root);
}
public void print_inorder(Node node) {
if (node == null) {
return;
}
print_inorder(node.left_child);
System.out.print(node.key + " ");
print_inorder(node.right_child);
}
public void print_preorder() {
print_preorder(root);
}
public void print_preorder(Node node) {
if (node == null) {
return;
}
System.out.print(node.key + " ");
print_preorder(node.left_child);
print_preorder(node.right_child);
}
public void print_postorder() {
print_postorder(root);
}
public void print_postorder(Node node) {
if (node == null) {
return;
}
print_postorder(node.left_child);
print_postorder(node.right_child);
System.out.print(node.key + " ");
}
}
This will have a node to the left if a number is even and a node to the right if a node is odd.
I had to change your if condition because the way it was it was never going to use the left node.
private void insert(Node x, int k) {
Node p = new Node(k);
if (root == null) {
this.root = p;
return;
}
if (x.getKey() - k % 2 == 0) {
if (x.left_child == null) {
x.left_child = p;
} else {
insert(x.left_child, k);
}
} else {
if (x.right_child == null) {
x.right_child = p;
} else {
insert(x.right_child, k);
}
}
}

Time out issue in java

I have been running this code and it seems like it times out. I'm not sure how to fix it as it doesn't show me an actual error message or anything like that. The first block of code is the class that the methods in the demo are coming from, and it seems like all the methods that are being called for stringList are just not working. When I test the same thing with an int list it works fine.
public class DoublyLinkedList<E> {
private static class Node<E> {
// Node Fields
private E element; //data
private Node<E> prev; //previous Node
private Node<E> next; //next Node
// Node Constructor
public Node(E e, Node<E> p, Node<E> n) {
this.element = e;
this.prev = p;
this.next = n;
}
// Node Methods
public E getElement() {
return element;
}
public Node<E> getPrev() {
return this.prev;
}
public Node<E> getNext() {
return this.next;
}
public void setPrev(Node<E> p) {
this.prev = p;
}
public void setNext(Node<E> n) {
this.next = n;
}
}
// DLinkedList Fields
private Node<E> header;
private Node<E> trailer;
int size;
// DLinkedList Constructor
public DoublyLinkedList() {
this.header = new Node<>(null, null, null);
this.trailer = new Node<>(null, this.header, null);
this.header.setNext(this.trailer);
}
// DLinkedList Methods
public int size() {
return this.size;
}
public E first() {
if (isEmpty()) {
return null;
}
return this.header.next.getElement();
}
public E last () {
if (isEmpty()) {
return null;
}
return this.trailer.prev.getElement();
}
public boolean isEmpty() {
return size == 0;
}
public void addFirst (E e) {
addBetween(e, this.header, this.header.getNext());
}
public void addLast (E e) {
addBetween(e, this.trailer.getPrev(), this.trailer);
}
private void addBetween(E e, Node<E> predecessor, Node<E> successor) {
Node<E> newest = new Node<>(e, predecessor, successor);
predecessor.setNext(newest);
successor.setPrev(newest);
this.size++;
}
public E removeFirst() {
if (this.isEmpty()) {
return null;
}
return this.remove(header.getNext());
}
public E removeLast() {
if (this.isEmpty()) {
return null;
}
return this.remove(trailer.getPrev());
}
public E remove(Node<E> e) {
e.next.setPrev(e.prev);
e.prev.setNext(e.next);
this.size--;
return e.getElement();
}
public String toString() {
StringBuilder sb = new StringBuilder("(");
Node<E> walk = this.header.next;
while (walk != this.trailer) {
sb.append(walk.element);
if (walk.next != this.trailer)
sb.append(", ");
walk = walk.next;
}
sb.append(")");
return sb.toString();
}
//DONE
public void add(int index, E element) {
Node<E> pred = header;
Node<E> succ = pred.getNext();
int count = 0;
while(succ != null) {
if(count == index) addBetween(element, pred, succ);
count++;
pred = pred.getNext();
succ = succ.getNext();
}
}
//DONE
public void add(E e) {
add(size, e);
}
//DONE
public void clear() {
while(!isEmpty()) {
removeFirst();
}
}
public E get(int index) {
if (isEmpty()) return null;
Node<E> current = header;
int count = 0;
while(current != null) {
if(count == index) return current.getElement();
count++;
current = current.getNext();
}
return null;
}
public E set(int index, E element) {
if(isEmpty()) return null;
Node<E> current = header;
E returnVal = null;
int count = 0;
while(current != null) {
if(count == index) {
if(count == 0) {
returnVal = get(0);
removeFirst();
add(0, element);
}
else if(count == size) {
returnVal = get(size);
removeLast();
add(size, element);
}
else {
returnVal = get(index);
remove(current);
add(index, element);
}
}
}
return returnVal;
}
}
package labs;
public class DoublyLinkedListDemo {
public static void main(String[] args) {
//testing methods on a String DoublyList
DoublyLinkedList<String> stringList = new DoublyLinkedList<>();
stringList.addFirst("Strawberry");
stringList.addFirst("Banana");
stringList.addFirst("Apple");
stringList.set(0, stringList.get(1));
System.out.println(stringList);
stringList.add(1, "Pear");
System.out.println(stringList);
stringList.add("Blueberry");
System.out.println(stringList);
System.out.println(stringList.get(1));
stringList.clear();
System.out.println(stringList);
System.out.println(stringList.set(0, stringList.get(1)));
System.out.println(stringList.get(0));
}
}

binary search and inorder traversal in Java

i'm studying a Binary Search Tree.
I use method inOrder kind of traversals but in main method i get an error. The question is why? What do i miss?
Thank you
inOrder(S11.Tree<java.lang.Integer>.Node<java.lang.Integer>)
in Tree cannot be applied to(S11.Node<java.lang.Integer>)
public class Tree<T extends Comparable<T>> {
private Node<T> root;
public void add(T data) {
root = doInsert(root, data);
}
public Node<T> doInsert(Node<T> root, T data) {
if (root == null) {
return new Node<T>(data);
} else if (data.compareTo(root.data) > 0) {
root.right = doInsert(root.right, data);
} else if (data.compareTo(root.data) < 0) {
root.left = doInsert(root.left, data);
}
return root;
}
public void inOrder(Node<T> root) {
if (root != null) {
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
}
class Node<T> {
Node<T> left;
Node<T> right;
T data;
public Node(T data) {
this.data = data;
}
}
}
public static void main(String[] args) {
Tree<Integer> tree = new Tree<Integer>();
Node<Integer> root1 = new Node<>(8);
tree.add(3);
tree.add(10);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(4);
tree.add(7);
tree.add(13);
tree.add(18);
tree.inOrder(**root1)**;//here I get an error
}
}
You have a design problem here as well as incorrect implementation of add(T data) method.
public final class Tree<T extends Comparable<T>> {
private Node<T> root;
private int size;
public void add(T val) {
Node<T> node = new Node<>(val);
if (root == null)
root = node;
else
add(root, node);
size++;
}
private void add(Node<T> parent, Node<T> node) {
if (node.val.compareTo(parent.val) < 0) {
if (parent.left == null)
parent.left = node;
else
add(parent.left, node);
} else if (parent.right == null)
parent.right = node;
else
add(parent.right, node);
}
public List<T> inOrder() {
return size == 0 ? Collections.emptyList() : Collections.unmodifiableList(inOrder(root, new ArrayList<>(size)));
}
private static <T> List<T> inOrder(Node<T> node, List<T> res) {
while (true) {
if (node == null)
return res;
inOrder(node.left, res);
res.add(node.val);
node = node.right;
}
}
// This is an internal implementation of Tree and should be hidden
// Node should not be linked with Tree instance
private static final class Node<T> {
private final T val;
private Node<T> left;
private Node<T> right;
public Node(T val) {
this.val = val;
}
}
}
Output:
Tree<Integer> tree = new Tree<>();
tree.add(8);
tree.add(3);
tree.add(10);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(4);
tree.add(7);
tree.add(13);
tree.add(18);
System.out.println(tree.inOrder()); // [1, 3, 4, 6, 7, 8, 10, 13, 14, 18]

Equals method to compare two trees

I have been learning java recently. And I created two trees. I need to write code(equals method) to compare two trees and if they are the same, then output true or false.
My Code:
public class TreePrint {
public static void main(String[] args) {
Tree<String> rootFolder = new Tree<>("RootFolder");
Node<String> video = rootFolder.addChild("Video");
Node<String> music = rootFolder.addChild("Music");
Node<String> picture = rootFolder.addChild("Picture");
video.addChild("Terminator");
video.addChild("Die Hard");
video.addChild("Rocky");
music.addChild("Eminem");
Node<String> picture01 = picture.addChild("Picasso");
picture01.addChild("Do Vinci");
Node<String> picture02 = picture01.addChild("Adil");
picture02.addChild("Cartoon");
picture02.addChild("Comics");
Tree2<String> rootFolder1 = new Tree2<>("RootFolder1");
Node<String> video1 = rootFolder1.addChild("Video");
Node<String> music1 = rootFolder1.addChild("Music");
Node<String> picture1 = rootFolder1.addChild("Picture");
video1.addChild("Terminator");
video1.addChild("Die Hard");
video1.addChild("Rocky");
music1.addChild("Eminem");
Node<String> picture001 = picture1.addChild("Picasso");
picture001.addChild("Do Vinci");
Node<String> picture002 = picture001.addChild("Adil");
picture002.addChild("Cartoon");
picture002.addChild("Comics");
printTree(rootFolder);
printTree(rootFolder1);
boolean b1 = rootFolder.contains("P0");
System.out.println(b1);
boolean b2 = rootFolder1.contains("Eminem");
System.out.println(b2);
}
private static <T> void printTree(Node<T> node) {
printTree(node, 0);
}
private static <T> void printTree(Node<T> node, int level) {
printNode(node, level);
if (node.getChildren() != null) {
for (Node childNode : node.getChildren()) {
printTree(childNode, level + 1);
}
}
}
private static <T> void printNode(Node<T> kid, int level) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(kid.getData());
}
}
first tree:
public class Tree<T> extends Node<T> {
public Tree(T data) {
super(data, null);
}
public boolean contains(T value) {
return recurse(iterate(), value);
}
private boolean recurse(List<Node<T>> children, T value) {
return children.stream()
.anyMatch(item -> item.getData().equals(value) || item.iterate().size() > 0 && recurse(item.iterate(), value));
}
}
public class Node<T> {
private T data;
private final List<Node<T>> children = new ArrayList<>();
private final Node<T> parent;
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
public void addChild(Node<T> node) {
children.add(node);
}
public Node<T> addChild(T nodeData) {
Node<T> newNode = new Node<T>( nodeData, this );
children.add( newNode );
return newNode;
}
public List<Node<T>> iterate() {
return children;
}
public void remove(Node<T> node) {
children.remove(node);
}
public List<Node<T>> getChildren() {
return children;
}
public Node getParent() {
return parent;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
Second Tree:
public class Tree2<T> extends Node<T> {
public Tree2(T data) {
super(data, null);
}
public boolean contains(T value) {
return recurse(iterate(), value);
}
private boolean recurse(List<Node<T>> children, T value) {
return children.stream()
.anyMatch(item -> item.getData().equals(value) || item.iterate().size() > 0 && recurse(item.iterate(), value));
}
}
Add the following method to your Node class. Since your tree is also a node - you should be able to compare two trees. FYI, This is autogenerated by Eclipse.
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (children == null) {
if (other.children != null)
return false;
} else if (!children.equals(other.children))
return false;
if (data == null) {
if (other.data != null)
return false;
} else if (!data.equals(other.data))
return false;
return true;
}
/* Given two trees, return true if they are
structurally identical */
boolean identicalTrees(Node a, Node b)
{
/*1. both empty */
if (a == null && b == null)
return true;
/* 2. both non-empty -> compare them */
if (a != null && b != null)
return (a.data == b.data
&& identicalTrees(a.left, b.left)
&& identicalTrees(a.right, b.right));
/* 3. one empty, one not -> false */
return false;
}
then just use this method for the root nodes of your two trees.

Implement multiset using sorted linkedList

Hello I implemented a multiset using a linkedlist and I want to implement the multiset using sorted linkedlist. This is multiset abstract class.
import java.io.PrintStream;
public abstract class Multiset<T> {
/**
* Delimiter string for print operation.
*/
protected static final String printDelim = " | ";
public abstract void add(T item);
public abstract int search(T item);
public abstract void removeOne(T item);
public abstract void removeAll(T item);
public abstract void print(PrintStream out);
}
This is my implementation of linkedlist.
import java.io.PrintStream;
public class LinkedListMultiset<T> extends Multiset<T> {
protected Node mHead;
protected int mLength;
public LinkedListMultiset() {
// Implement me!
mHead = null;
mLength = 0;
}
public void add(T item) {
Node newNode = new Node((String) item);
if (mHead == null)
mHead = newNode;
else {
Node currNode = mHead;
Node parentNode = null;
while (currNode != null) {
if (currNode.getValue().
equals(newNode.getValue())) {
currNode.addCounter();
return;
}
parentNode = currNode;
currNode = currNode.getNext();
}
parentNode.setNext(newNode);
}
mLength++;
}
public int search(T item) {
Node currNode = mHead;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
return currNode.getCounter();
}
currNode = currNode.getNext();
}
return 0;
}
public void removeOne(T item) {
Node currNode = mHead;
Node lastNode = null;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
currNode.minusCounter();
if (currNode.getCounter() == 0) {
if (currNode == mHead)
mHead = currNode.getNext();
else
lastNode.setNext
(currNode.getNext());
mLength--;
}
return;
}
lastNode = currNode;
currNode = currNode.getNext();
}
}
public void removeAll(T item) {
Node currNode = mHead;
Node lastNode = null;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
if (currNode == mHead)
mHead = currNode.getNext();
else
lastNode.setNext(currNode.getNext());
mLength--;
return;
}
lastNode = currNode;
currNode = currNode.getNext();
}
}
public void print(PrintStream out) {
Node currNode = mHead;
while (currNode != null) {
out.printf("%s | %d\n", currNode.getValue()
, currNode.getCounter());
currNode = currNode.getNext();
}
}
private class Node {
protected String mValue;
protected Node mNext;
int counter;
public Node(String value) {
mValue = value;
mNext = null;
counter = 1;
}
public void addCounter() {
counter++;
}
public void minusCounter() {
counter--;
}
public int getCounter() {
return counter;
}
public String getValue() {
return mValue;
}
public Node getNext() {
return mNext;
}
public void setValue(String value) {
mValue = value;
}
public void setNext(Node next) {
mNext = next;
}
}
}
I want to implement sorted linkedlist but I want to change my code as minimum as possible.

Categories