Thanks for the description. Oddly, this is the second question in 2 days where a binary tree was specified with the node numbers. Go figure.
Anyway, given the root of the longest path, there are two possibilities:
1. the path starts at the root and runs down through a bunch of descendents, or
2. the path starts down the left tree, runs up through the root, and then goes down the right tree.
My solution is more complicated than I thought it would be. Perhaps there's an easier way. I distinguished between a
string of vowels, which is a string that starts at a node and runs through the descendents, and a
chain of vowels, which can be a string, or, if both children are vowels, then the it starts down one child, runs up through the current node, and then down the other. So a string is case 1 and a chain is case 2.
Each node stores the length of the longest string rooted at that node. I stored the nodes in a vector and the left and right "pointers" are really indices into the vector
1 2 3 4 5 6 7 8 9 10
|
struct Node {
char ch = 0;
// index into nodes of the left & right trees. zero means none
unsigned left=0, right=0;
// length of the longest string of vowels starting with this node
// and running down through the descendents.
unsigned length=0;
};
vector<Node> nodes;
|
A helper function computes the length of the longest chain in a subtree that also runs through the subtree's root:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
unsigned longestChain(unsigned idx)
{
if (idx == 0) return 0;
Node &node(nodes[idx]);
if (!isVowel(node.ch)) {
return 0;
}
unsigned rightLen = (node.right ? nodes[node.right].length : 0U);
unsigned leftLen = (node.left ? nodes[node.left].length : 0U);
unsigned result = 1 + rightLen+leftLen;
return result;
}
|
You could store that length too I suppose but it seemed easy to compute.
Finally, there's the recursive function. It needs to do a lot:
- Call itself on its children
- set the length of the longest
string rooted at this node.
- compute the length of the longest
chain through this node.
- return the index of the node that contains the longest chain in the subtree.
I stored length as the number of nodes in a string or chain, not the number of edges. That way a node with a vowel and no children has a chain length of 1, which a node iwth a non-vowel has a chain length of 0.
When the recursive function returns the index of the root of the longest chain, you have to print it:
- recursively print the longest string of the left child
- print the node's index
- recursively print the longest string of the right child.