Self-referential Structure Tree
C
Hard
3 views
Problem Description
Create a binary tree node (data, left pointer, right pointer). Manually create a tree of 7 nodes and traverse it (inorder, preorder, postorder).
Official Solution
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node *left;
struct Node *right;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Inorder traversal: Left, Root, Right
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
// Preorder traversal: Root, Left, Right
void preorder(struct Node* root) {
if (root != NULL) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
// Postorder traversal: Left, Right, Root
void postorder(struct Node* root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}
int main() {
// Manually create a tree of 7 nodes
// 1
// /
// 2 3
// / /
// 4 5 6 7
struct Node *root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
printf("Inorder Traversal: ");
inorder(root);
printf("n");
printf("Preorder Traversal: ");
preorder(root);
printf("n");
printf("Postorder Traversal: ");
postorder(root);
printf("n");
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!