All Root to Leaf Paths
5
/ \
/ \
1 8
\ /\
\ / \
3 6 9
[5, 1, 3]
[5, 8, 6]
[5, 8, 9]template<typename T>
void root_leaf_paths(Node<T> *root, vector<T> &temp, vector<vector<T>> &main) {
if (root) {
temp.push_back(root->value);
if (!root->left && !root->right) {
main.push_back(temp);
temp.pop_back();
return;
}
if (root->left) root_leaf_paths(root->left, temp, main);
if (root->right) root_leaf_paths(root->right, temp, main);
}
temp.pop_back();
}
template<typename T>
vector<vector<T>> root_leaf_paths(BST<T> *tree) {
vector<vector<T>> main;
vector<T> temp;
root_leaf_paths(tree->root, temp, main);
return main;
}
int main()
{
vector<int> stuff = { 4,2,6,1,5,3,7,9,10,8,23 };
BST<int> *tree = new BST<int>();
cout << "INSERTING ... " << endl;
//srand(time(nullptr));
for (auto i : stuff) {
cout << i << " ";
tree->insert(i);
}
cout << endl << endl;
//pause();
cout << "OUR TREE ... " << endl;
tree->prettyPrint_levelOrder();
cout << endl << endl;
//pause();
vector<vector<int>> paths = root_leaf_paths(tree);
print2d(paths);
}Last updated