Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Language IDEs » Java Development Tools (JDT) » Help with Preorder Traversal in C++ -
Help with Preorder Traversal in C++ - [message #1861129] Fri, 22 September 2023 07:43 Go to next message
Ashley coder is currently offline Ashley coderFriend
Messages: 11
Registered: October 2022
Junior Member
Hello to everyone.

I've been researching data structures and algorithms, and I stumbled found this fantastic preorder traversal lesson online. I'm attempting to implement it in C++, but I'm experiencing some difficulties. The instruction may be found here: Tutorial on preorder traversal of binary tree.

I understand the notion of preorder traversal, but I'm having trouble writing the code in C++. Could you kindly supply a code sample or lead me through the phases of implementation? It would be much appreciated.

So far, here's what I've tried:


#include <iostream>
using namespace std;

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;
    }
    cout << root->val << " ";
    preorderTraversal(root->left);
    preorderTraversal(root->right);
}

int main() {
    // Sample tree creation
    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);

    cout << "Preorder Traversal: ";
    preorderTraversal(root);

    return 0;
}


I'm not sure if my code is correct or if I'm missing something. Any help or guidance would be awesome!

[Updated on: Fri, 22 September 2023 07:45]

Report message to a moderator

Re: Help with Preorder Traversal in C++ - [message #1861130 is a reply to message #1861129] Fri, 22 September 2023 08:26 Go to previous message
Ed Merks is currently offline Ed MerksFriend
Messages: 33264
Registered: July 2009
Senior Member
I guess you didn't notice this is the JDT forum, not a CDT forum. I don't think it's even good question for the CDT discussions because you're not asking a question about the tool

https://github.com/eclipse-cdt/cdt/discussions

Better to ask on some general forum like stackoverflow.


Ed Merks
Professional Support: https://www.macromodeling.com/
Previous Topic:Java 21 Unnamed Classes and Instance Main Methods Support in IDE
Next Topic:Understanding the KMP Algorithm for Efficient Pattern Searching in Java
Goto Forum:
  


Current Time: Mon Jan 13 08:19:58 GMT 2025

Powered by FUDForum. Page generated in 0.03130 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top