Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented count(), toString() #20

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions src/Tree.java
Original file line number Diff line number Diff line change
@@ -1,2 +1,114 @@
import java.util.ArrayList;
import java.util.Optional;

public class Tree {


/**
* The person's name (family name last).
*/
private Optional<Object> root;
/**
* The person's UTORid
*/
ArrayList<Tree> subtrees;

/**
* Initialize this Person named name with UTORid utorid.
*
* @param root the person's name (family name last)
* @param subtrees the person's UTORid
*/
Tree (Optional<Object> root, ArrayList<Tree> subtrees) {
/** Initialize a new Tree with the given root value and subtrees.

If <root> is None, the tree is empty.
Precondition: if <root> is None, then <subtrees> is empty.
*/

this.root = root;
if (subtrees == null) {
this.subtrees = new ArrayList<Tree>();

} else {
this.subtrees = new ArrayList<>(this.subtrees);

}


}


Tree () {
/** Initialize a new Tree with the given root value and subtrees.

If <root> is None, the tree is empty.
Precondition: if <root> is None, then <subtrees> is empty.
*/

this.root = root;
this.subtrees = new ArrayList<Tree>();

}

boolean isEmpty() {
return this.root == null;
}

int size() {
if (this.isEmpty()) {
return 0;
} else {
int size = 1;
for (Tree subtree : this.subtrees) {
size += subtree.size();
}
return size;
}


}
}
public int count(Object item) {

if (this.is_empty()) {
return 0;
} else {

int num = 0;

if (this.root == item) {
num += 1;
}

for (Tree subtree : this.subtrees) {
num += subtree.count(item);
}

return num;
}
}

public String toString() {
return this.str_indented();
}

private String str_indented(int depth) {

if (this.is_empty()) {
return "";
} else {
String s = " ".repeat(depth) + toString(this.root) + "\n";
for (Tree subtree : this.subtrees) {
s += subtree.str_indented(depth + 1);
}

return s;

}
}

private String str_indented() {
return this.str_indented(0);
}
}