题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

struct TreeNode *reConstructBinaryTree(int *pre, int preLen, int *vin, int vinLen)
{
  // write code here
  struct TreeNode *root;
  root = (struct TreeNode *)malloc(sizeof(struct TreeNode));

  //注意边界条件,划分到叶子节点时会出现pre不是NULL,但prelen==0
  if (!pre || preLen == 0)
    return NULL;
  //找到vin里在pre中第一个出现的节点位置对pre是first,对vin是切割点
  int first = 0, cut = 0;
//这里因为肯定能找到,用while循环不会死循环,这样的话就会比for方便
  while (pre[first] != vin[cut])
    cut++;

  root->val = pre[first];

  root->left = reConstructBinaryTree(pre + 1, cut, vin, cut - 1);
  root->right = reConstructBinaryTree(pre + cut + 1, preLen - cut - 1, vin + cut + 1, vinLen - cut - 1);

  return root;
}

全部评论
个人认为这个算法在运行较大规模的数时效果并不理想,个人测试了三个模范数据,只有数据最少的那个通过了编译,其他的都有着溢出的问题
点赞 回复 分享
发布于 2022-03-19 14:15

相关推荐

星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务