• 两种方法C实现二叉树的创建和遍历


    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct node {
    	int data;
    	struct node *left;
    	struct node *right;
    } node_t;
    
    typedef struct tree {
    	struct node *root;
    } tree_t;
    
    
    node_t *alloc_one(int data) {
    	node_t *p = (node_t *)malloc(sizeof(node_t));
    	p->data = data;
    	p->left = NULL;
    	p->right = NULL;
    
    	return p;
    }
    
    // 方法1:
    void insert_one(tree_t *t, int data) {
    	node_t *new = alloc_one(data);
    
    	if (t == NULL) {
    		t = new;
    	} else {
    		node_t *tmp = t->root;
    
    		while (tmp) {
    			if (data < tmp->data) {
    				if (tmp->left == NULL) {
    					tmp->left = new;
    					return;
    				} else {
    					tmp = tmp->left;
    				}
    			} else if (data > tmp->data) {
    				if (tmp->right == NULL) {
    					tmp->right = new;
    					return;
    				} else {
    					tmp = tmp->right;
    				}
    			}
    		}
    	}
    }
    
    // 方法2:递归法
    node_t *insert_one2(node_t *t, int data) {
    	node_t *new = alloc_one(data);
    
    	if (t == NULL) {
    		t->root = new;
    	} else {
    		node_t *tmp = t->root;
    
    		if (data < tmp->data) {
    			if (tmp->left == NULL) {
    				tmp->left = new;
    				return tmp->left;
    			} else {
    				insert_one2(tmp->left, data);
    			}
    		} else {
    			if (tmp->right == NULL) {
    				tmp->right = new;
    				return tmp->right;
    			} else {
    				insert_one2(tmp->right, data);
    			}
    		}
    	}
    
    	return t;
    }
    
    
    void inOrder(struct node_t *root, int *res, int *resSize) {
    
    	if (!root) {
    		return;
    	}
    
    	inOrder(root->left, res, resSize);
    	res[(*resSize++)] = root->data;
    	inOrder(root->right, res, resSize);
    }
    
    int* inOrderTraverse(struct node_t *root, int *returnSize) {
    	int *res = malloc(sizeof(int) * 100);
    	*returnSize = 0;
    
    	inOrder(root, res, returnSize);
    }
    
    int main() {
    	int dataList[3] = {3, 5, 19};
    	int i;
    
    	tree_t *my_tree;
    	my_tree->root = NULL;
    
    	for(i = 0; i < sizeof(dataList)/sizeof(int); i++) {
    		insert_one(my_tree, i);
    	}
    
    	return 0;
    }
    
    
    muahao@aliyun.com
  • 相关阅读:
    HTTP 错误 403.14
    HTTP 错误 404.3
    HTTP 500
    [转]ESCAPE()、ENCODEURI()、ENCODEURICOMPONENT()区别详解
    此计算机当前已将连接限制
    一个由表结构生成表的存储过程
    微信小程序页面跳转传参
    前端性能优化术语
    get请求和post请求的区别
    从输入url到页面呈现的过程
  • 原文地址:https://www.cnblogs.com/muahao/p/14639644.html
Copyright © 2020-2023  润新知