面试题6:重建二叉树

  1 /*主函数:重建二叉树*/
  2 bool treeBuild(int *arrayBefore, int *arrayMiddle, int length, TreeNode * treeRoot)
  3 {
  4     int key;
  5     int leftLenth = 0;
  6     int rightLenth = 0;
  7     bool result;
  8 
  9     /*1.合法性检查*/
 10     if((NULL == arrayBefore)&&(NULL == arrayMiddle))
 11     {
 12         return false;
 13     }
 14     if((NULL == treeRoot)||(length <= 0))
 15     {
 16         return false;
 17     }
 18 
 19     /*2.找到分段点*/
 20     key = arrayBefore[0];
 21     while(leftLenth < length)
 22     {
 23         if(key == arrayMiddle[leftLenth])
 24         {
 25             break;
 26         }
 27         else
 28         {
 29             leftLenth++;
 30         }
 31     }
 32 
 33     /*3.重建左子节点*/
 34     if(leftLenth != 0)
 35     {
 36         treeRoot->left = (TreeNode *)malloc(sizeof(TreeNode));
 37         treeRoot->left->left = NULL;
 38         treeRoot->left->right = NULL;
 39         result = treeBuild(arrayBefore+1, arrayMiddle, leftLenth, treeRoot->left);
 40         if(false == result)
 41         {
 42             freeTreeNode(treeRoot->left);
 43             return false;
 44         }
 45     }
 46 
 47     /*4.重建右子节点*/
 48     rightLenth = length - 1 - leftLenth;
 49     if(rightLenth != 0)
 50     {
 51         treeRoot->right = (TreeNode *)malloc(sizeof(TreeNode));
 52         treeRoot->right->left = NULL;
 53         treeRoot->right->right = NULL;
 54         result = treeBuild(arrayBefore + 1 + leftLenth, arrayMiddle + 1 + leftLenth, rightLenth, treeRoot->right);
 55         if(false == result)
 56         {
 57             freeTreeNode(treeRoot->left);
 58             freeTreeNode(treeRoot->right);
 59             return false;
 60         }
 61     }
 62 
 63     treeRoot->value = key;
 64     return true;
 65 }
 66 
 67 /*辅助函数:后序打印*/
 68 void printTreeNode(TreeNode * treeRoot)
 69 {
 70     if(NULL == treeRoot)
 71     {
 72         return;
 73     }
 74 
 75     printTreeNode(treeRoot->left);
 76     printTreeNode(treeRoot->right);
 77     printf("%d ", treeRoot->value);
 78     return;
 79 }
 80 
 81 /*辅助函数:释放所有节点*/
 82 void freeTreeNode(TreeNode * treeRoot)
 83 {
 84     if(NULL == treeRoot)
 85     {
 86         return;
 87     }
 88 
 89     if(NULL != treeRoot->left)
 90     {
 91         freeTreeNode(treeRoot->left);
 92         treeRoot->left = NULL;
 93     }
 94     
 95     if(NULL != treeRoot->right)
 96     {
 97         freeTreeNode(treeRoot->right);
 98         treeRoot->right = NULL;
 99     }
100 
101     free(treeRoot);
102     treeRoot = NULL;
103 
104     return;
105 }
原文地址:https://www.cnblogs.com/cauchy007/p/4559069.html