So I was doing this leetcode question and didn't understand what was happening. It is about preorder traversal through a binary tree.
At first I thought it would be simple enough to implement the traversal code I learned in class.
vector<int> preorderTraversal(TreeNode* root) {
vector<int> final;
if(root == nullptr){
return final;
}
final.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
return final;
}
but then I hit a snag when the code hit a NULL in the left child of the root in one of the test cases.
I scratched my head at what I could do recursively to bypass this problem until I looked at some of the solutions that were posted.
vector<int>ar1;
void preOrder(TreeNode *root)
{
if(root==nullptr)
return;
ar1.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
vector<int> preorderTraversal(TreeNode* root)
{
preOrder(root);
return ar1;
}
My question is what makes their traversals using a different method than doing it in the first code snippet?