Rishab7
New Member
- Joined
- Apr 17, 2023
- Messages
- 21
- Thread Author
- #1
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:
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!
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!