I'm working through a tree traversal problem and using 'push_back' vector function to update a vector with the in-order traversal. Alongside using this I am using cout to print out the solution to debug. The print output is correct but my returning vector doesn't match the print so I can only put this down to me not understanding how the push_back function works.
This is the function I am using:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> order {};
if (root != nullptr) {
inorderTraversal(root->left);
cout << "pushing back : " << root->val << std::endl;
order.push_back(root->val);
inorderTraversal(root->right);
}
return order;
}
For the input tree [1,null,2,3] My stdout is printing:
pushing back : 1 pushing back : 3 pushing back : 2
Which is correct but my returning array (order) is only [1].
You're ignoring the results from each recursion. You should be doing this:
vector<int> inorderTraversal(TreeNode *root)
{
vector<int> order;
if (root != nullptr)
{
order = inorderTraversal(root->left);
cout << "pushing back : " << root->val << std::endl;
order.push_back(root->val);
auto tmp = inorderTraversal(root->right);
order.insert(order.end(), tmp.begin(), tmp.end());
}
return order;
}
Much More Efficient
That said, if you counted the number of local vectors created in this, though short, they will be many (as many as there are nodes in your tree, in fact). You can eliminate all of those middle-men vectors by providing a shim between the actual traversal and the creation of the order vector:
void inorderTraversal_v(TreeNode const *root, std::vector<int>& order)
{
if (root != nullptr)
{
inorderTraversal(root->left, order);
order.push_back(root->val);
inorderTraversal(root->right, order);
}
return order;
}
std::vector<int> inorderTraversal(TreeNode const *root)
{
std::vector<int> order;
inorderTraversal_v(root, order);
return order;
}
Doing this creates a single vector, and in so doing eliminates (N-1) temporary vectors along the way, where N is the number of nodes in the tree.