《剑指Offer》面试题6 重建二叉树——勘误

感觉是个小bug:

// 在中序遍历中找到根结点的值
int* rootInorder = startInorder;
while(rootInorder <= endInorder && *rootInorder != rootValue)
  ++ rootInorder;
if(rootInorder == endInorder && *rootInorder != rootValue)
  throw std::exception("Invalid input.");

下面的if判断,其初衷是,如果在中序中没有找到根结点,报错。
例如:输入的前序是:{1, 2, 4, 7, 3, 5, 6, 8}
输入的中序是:{4, 7, 2, 9, 5, 3, 8, 6}
根结点1,在中序中查找,一直查到中序数组的末尾也没找到。按上面的逻辑,是rootInorder一直取到了8。
在if判断中,rootInorder == endInorder,rootInorder 的地址已经越出了数组的界,后面的判断条件不会使用。按理说第一个根结点就找不到,就会直接报异常,终止程序。
但按原文的代码,会继续下面的构建子树。
其实也就一个小bug,改动如下:

//如果在中序序列中没找到前序中对应的根结点
if(rootInorder > endInorder ) throw std::exception("Invalid input.");
原文地址:https://www.cnblogs.com/zhouqg/p/4779594.html