BinaryTree
unknown
c_cpp
3 years ago
1.4 kB
7
Indexable
Never
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *left; struct node *right; }; struct node * add(struct node * root,int newData){ if (root==NULL) { struct node * root = (struct node *)malloc(sizeof(struct node)); root->data=newData; root->left=NULL; root->right=NULL; return root; } struct node * tmp = root; if (tmp->data<newData) tmp->right = add(tmp->right,newData); if (tmp->data >newData) tmp->left = add(tmp->left,newData); } void pre_order_traversal(struct node* root) { if (root==NULL) return; if(root != NULL) { printf("%d ",root->data); pre_order_traversal(root->left); pre_order_traversal(root->right); } } void inorder_traversal(struct node* root) { if (root==NULL) return; if(root != NULL) { inorder_traversal(root->left); printf("%d ",root->data); inorder_traversal(root->right); } } void post_order_traversal(struct node* root) { if (root==NULL) return; if(root != NULL) { post_order_traversal(root->left); post_order_traversal(root->right); printf("%d ", root->data); } } int main(){ struct node * tree1 = NULL; tree1 = add(tree1,5); tree1 = add(tree1,17); tree1 = add(tree1,21); tree1 = add(tree1,19); pre_order_traversal(tree1); }