今天群上一个人说递归的二叉树插入不知道怎么做,于是我就帮忙写了个简单的demo
// binary_tree.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
typedef struct node{
int value;
node* left;
node* right;
}node;
/*print the tree left-mid-right order*/
void printTree(node* root){
if(root == NULL)
return;
printTree(root->left);
printf("%d,",root->value);
printTree(root->right);
}
/*make node*/
node* makeNode(){
node* n = (node*) malloc(sizeof(node));
n->value = 0;
n->left = NULL;
n->right = NULL;
return n;
}
/*to insert a value into the binary tree, return the new root*/
node* insert(node* root, int value){
if(root == NULL){
root = makeNode();
root->value = value;
}else if(value < root->value){// insert to the left
root->left = insert(root->left,value);
}else{// insert to the right
root->right = insert(root->right,value);
}
return root;
}
int main(int argc,char* argv[]){
node* root = NULL;
int data[10] = {3,2,1,4,6,8,7,10,9,33};
for(int i=0;i<10;i++){
root = insert(root,data[i]);
}
printTree(root);
system("pause");
return 0;
}