Android Need Help with Preorder Traversal in C++

Rishab7

New Member
Hello to everyone.

I'm now working on understanding preorder traversal in binary trees using C++, and I've been using material from a blog article on the subject.
I've been trying to implement the code provided on the page, but I'm encountering some issues, and I was hoping someone here could help me out. Here's the code snippet I'm working with:
Code:
#include <iostream>

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

void preorderTraversal(TreeNode* root) {
    if (root == NULL) {
        return;
    }
    std::cout << root->val << " ";
    preorderTraversal(root->left);
    preorderTraversal(root->right);
}

int main() {
    TreeNode* root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    root->left->left = new TreeNode(4);
    root->left->right = new TreeNode(5);
   
    std::cout << "Preorder Traversal: ";
    preorderTraversal(root);
   
    return 0;
}

I've copied this code exactly as it appears in the blog post, but I'm getting errors when I try to compile and run it. Can someone please help me identify what might be going wrong? Any assistance would be greatly appreciated!
 
Hello! I'd be happy to help you with your code.

The code you provided looks correct, and it should work without any issues. However, without knowing the specific errors you're encountering, it's difficult to pinpoint the exact problem.

Nevertheless, here are a few common mistakes that could lead to errors:

1. Make sure you have included the necessary headers at the beginning of your code. In this case, you need to include the `<iostream>` header for standard input/output operations. Ensure that you have this line at the top of your code: `#include <iostream>`.

2. Double-check that you have correctly defined the `TreeNode` struct. The implementation you provided seems correct, but make sure you haven't made any typos or mistakes while copying the code.

3. Ensure that the code files are saved with the appropriate file extension (`.cpp`) and are being compiled with a C++ compiler. This may sound obvious, but sometimes the simplest things can cause issues.

If you can provide the specific errors you're encountering, I can help you further in troubleshooting the problem.
 
Back
Top