I have this n-ary tree implementation, where each tree class stores the data and it's children in an array.
Also there is my incomplete method equals()
.
public class ArrayNTree<T extends Comparable<T>> implements NTree<T>, Cloneable {
/* Data of the tree*/
private T data;
/* Primary array to store the children */
private ArrayNTree<T>[] children;
...
public boolean equals(Object other) { // FIXME
if (this == other)
return true;
if (other == null)
return false;
if(other instanceof ArrayNTree)
return sameTree( (ArrayNTree<T>) other );
return false;
}
private boolean sameTree(ArrayNTree<T> xpto) {
return (this.data == xpto.data &&
//this.children == xpto.children && ???????
this.size == xpto.size);
}
My main doubt is how do I go through every child and compare with the other tree since this is an array I think it makes the job a little harder
First, if data
or size
is different return false
Then, check its children
one by one:
private boolean sameTree(ArrayNTree<T> xpto) { if(this.data != xpto.data || this.size != xpto.size) return false; for(int i = 0; i<this.children.length: i++){ if(!this.children[i].equals(xpto.children[i])) return false; } return true; }
Using Arrays.deepEquals()
private boolean sameTree(ArrayNTree<T> xpto) { return this.data == xpto.data && this.size != xpto.size && Arrays.deepEquals(this.children, xpto.equals); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.