使用C语言构建基本的二叉树数据结构

2020-01-06 13:43:26王冬梅
  • */  btree* rebuildTree(char *order, char *post, int len);  

    算法思想

    中序序列:C、B、E、D、F、A、H、G、J、I

    后序序列:C、E、F、D、B、H、J、I、G、A

    递归思路:

    根据后序遍历的特点,知道后序遍历最后一个节点为根节点,即为A

    观察中序遍历,A左侧CBEDF为A左子树节点,A后侧HGJI为A右子树节点

    然后递归的构建A的左子树和后子树

    实现代码(c代码)

     

     
    1. /**   * 根据中序和后序序列构建二叉树  
    2. * (ps:昨晚参加阿里笔试,等到最后说可以免笔试直接面试,今天估计还是要根据学校筛选,哈哈,为了这点   * 也得参加阿里笔试,不能让自己的学校受到鄙视)  
    3. */   
    4. #include <stdio.h>   #include <stdlib.h>  
    5. #include <string.h>    
    6. int n;    
    7. typedef struct btree {   struct btree *lchild;  
    8. struct btree *rchild;   char data;  
    9. } btree;    
    10. /**   * 中序、后序序列构建二叉树  
    11. */  btree* rebuildTree(char *order, char *post, int len)  
    12. {   btree *t;  
    13.   if (len <= 0) {  
    14. return NULL;   } else {  
    15. int index = 0;