my question is how to use tail recursion to traverse the binary tree in the level order and print it in a specific format.
Binary Tree
__ 60 _
| |
__ 50 _ 100 _
| | |
30 55 1000
output "60 : 50, 100 : 30, 55, 1000"
my code snippet and it works:
void LevelOrderTraversalTailRecur(BinaryTreeNode* root, int level, vector<vector<int>>& vec) {
if (root == nullptr) return;
if (vec.size() < level) {
auto v{std::vector<int>{}};
vec.push_back(v);
}
vec[level - 1].push_back(root->data);
if (root->left != nullptr) {
LevelOrderTraversalTailRecur(root->left, level+1, vec);
}
if (root->right != nullptr) {
LevelOrderTraversalTailRecur(root->right, level+1, vec);
}
}
void LevelOrderTraversal(BinaryTreeNode* root) {
if (root == nullptr) {
cout << "null";
return;
}
std::vector<std::vector<int>> vec;
LevelOrderTraversalTailRecur(root, 1, vec);
// ....
// convert the vector into a string
}
But I would like to use the interface void LevelOrderTraversalTailRecur(BinaryTreeNode* root, int level, string &s) directly instead of vector<vector>. How can I achieve it?
Thanks!