Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- struct TreeNode {
- int data; //node value
- TreeNode* left; //pointer to left child
- TreeNode* right; //pointer to right child
- TreeNode(int value) { //constructor for initializing a node
- data = value;
- left = nullptr;
- right = nullptr;
- }
- };
- //Pre-order traversal - you start at the root node and then you visit the left subtree first and then the right
- void printPreOrder(TreeNode* root) {
- if (root != nullptr) {
- std::cout << root->data << " ";
- printPreOrder(root->left);
- printPreOrder(root->right);
- }
- }
- int main()
- {
- TreeNode* root = new TreeNode(1);
- root->left = new TreeNode(3);
- root->right = new TreeNode(4);
- root->left->left = new TreeNode(5);
- root->left->right = new TreeNode(8);
- printPreOrder(root);
- }
- // 1
- // / \
- // 3 4
- // / \
- // 5 8
Advertisement
Add Comment
Please, Sign In to add comment