public String toString () { // Perform a depth-first search (DFS) // with two stacks: one for the nodes (as in the usual DFS) // and another, parallel one, for their string prefixes // // A null on the Node stack means that the corresponding // string on the string stack needs to be output Stack nodeStack = new Stack(); Stack prefixStack = new Stack(); String ret = ""; if (root != null) { nodeStack.push(root); prefixStack.push(""); do { TernaryTreeNode n = nodeStack.pop(); String prefix = prefixStack.pop(); if (n == null) // print the string -- it's complete { ret+=prefix+"\n"; } else { // Push the right child first, so its popped last, // to ensure alphabetical order if (n.right != null) { nodeStack.push(n.right); prefixStack.push(prefix); } // Push the center child, regardless of whether it's null // (if it's not null, it needs to be traversed, else it needs // to be printed when it's popped off) nodeStack.push(n.center); prefixStack.push(prefix+n.splitChar); // Push the left child last, to ensure alphabetical order if (n.left != null) { nodeStack.push(n.left); prefixStack.push(prefix); } } } while (!nodeStack.isEmpty()); } return ret; }