打扰各位,亲手求教
这里是根据前序遍历和中序遍历,输出后续遍历的代码
小妹不懂得是,在函数递归调用时,length变量值的变化,求教
#include <iostream>
#include <fstream>
#include <string>
struct TreeNode
{
struct TreeNode* left;
struct TreeNode* right;
char elem;
};
void BinaryTreeFromOrderings(char* inorder, char* preorder, int length)
{
cout<<"leftlength "<<length<<endl;
if(length == 0)
{
//cout<<"invalid length";
return;
}
TreeNode* node = new TreeNode;//Noice that [new] should be written out.
node->elem = *preorder;
int rootIndex = 0;
for(;rootIndex < length; rootIndex++)
{
if(inorder[rootIndex] == *preorder)
break;
}
//Left
cout<<"FUNC前leftlength "<<length<<" rootindex "<<rootIndex<<endl;
BinaryTreeFromOrderings(inorder, preorder +1, rootIndex);
cout<<"leftlength "<<length<<" rootindex "<<rootIndex<<endl;
//Right
BinaryTreeFromOrderings(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1));
cout<<"right "<<length<<" rootindex "<<rootIndex<<endl;
cout<<node->elem<<endl;
return;
}
int main(int argc, char* argv[])
{
printf("Hello World!\n");
char* pr="GDAFEMHZ";
char* in="ADEFGHMZ";
BinaryTreeFromOrderings(in, pr, 8);
printf("\n");
return 0;
}
如图所示,我不能理解的是为什么左子树遍历结束时length的值是1,不是0呢。