I have a tree with the most frequent letters at the top of the tree and I am trying to find the path to a node so I can turn a message into binary. In this program if I go left, I add 0 to path
and, if I go right, I add 1 to the path
until I find the node. But I have to go straight to the desired node which is not possible. The only thing I could think of is removing the last character or path
if a node has no children, but it does not work if a node has grandchildren. Can someone help me on how to approach this? Thanks!
// global variables
String path;
int mark;
// encodes a message to binary
String encoder(char data) {
path = "";
mark = 0;
findPath(root, data);
return path;
}
// finds the path to a node
void findPath(TNode node, char data) {
if(node.data == data) {
mark = 1;
return;
}
if(mark==0 && node.left != null) {
path += 0;
findPath(node.left, data);
}
if(mark==0 && node.right != null) {
path += 1;
findPath(node.right, data);
}
if(mark==0 && node.left == null || node.right == null) {
path = path.substring(0, path.length() - 1);
}
}