It'd be easier to start from there than to try and chop up and repurpose your recursive code IMO.
public void toString(NodeImpl<E> node) {
if (node == root) {
treeToString.append(root.key + "(");
}
if (node.left == nil && node.right == nil) {
if (node == node.parent.right) {
}
}
if (node.left != nil) {
if (node.left.left != nil || node.left.right != nil) {
treeToString.append(node.left.key + "(");
toString(node.left);
} else {
if (node.right != nil) {
treeToString.append(node.left.key);
} else {
treeToString.append(node.left.key + ")");
}
toString(node.left);
}
}
if (node.right != nil) {
if (node.right.left != nil || node.right.right != nil) {
if (node.left != nil) {
treeToString.append("," + node.right.key + "(");
} else {
treeToString.append(node.right.key + "(");
}
toString(node.right);
} else {
if (node.left != nil) {
treeToString.append("," + node.right.key);
} else {
treeToString.append(node.right.key);
}
toString(node.right);
}
treeToString.append(")");
}
}
DFS(G,v) ( v is the vertex where the search starts )
Stack S := {}; ( start with an empty stack )
for each vertex u, set visited[u] := false;
push S, v;
while (S is not empty) do
u := pop S;
if (not visited[u]) then
// Print '('
// Print node name
visited[u] := true;
for each unvisited neighbour w of u
push S, w;
// Print ')'
end if
end while
END DFS()
private List<Node<E>> breadthFirst(Node<E> n) {
Queue<Node<E>> queue = new LinkedList();
LinkedList<Node<E>> output = new LinkedList();
if (n == null) {
return output;
}
queue.add(n);
while (!queue.isEmpty()) {
Node<E> node = queue.remove();
output.add(node);
if (left(node) != null) queue.add(left(node));
if (right(node) != null) queue.add(right(node));
}
return output;
}
Title | # Comments | Views | Activity |
---|---|---|---|
Eclipse IDE - Cannot copy/paste from console output | 8 | 58 | |
Java array passed to SQL where clause | 23 | 38 | |
backtracking recursion code | 19 | 39 | |
Hashing Algorithm | 5 | 26 |
Join the community of 500,000 technology professionals and ask your questions.
Connect with top rated Experts
6 Experts available now in Live!