二叉树的顺序表示法(" ' "代表有子结点,"/"代表空指针,无'代表无子结点)
可以把图6.16中的二叉树表示如下:
A'B'/DC'E'G/F'HI
从二叉树中读取的print函数C++算法代码:
1 template<class Elem> 2 void printhelp(BinNode*subroot) 3 { 4 if(subroot==NULL) cout<<"\\"; 5 else cout<<subroot->value(); 6 if((subroot->left==NULL)&&(subroot->right==NULL)) 7 return; 8 else cout<<"'"; 9 printhelp(subroot->left()); 10 printhelp(subroot->right()); 11 12 }
而从顺序表中解码为二叉树的convert函数C++算法代码:
1 template <class Elem> 2 BinNode<Elem>* convert(char* inlist) { 3 int curr = 0; 4 return converthelp(inlist, curr); 5 } 6 7 template <class Elem> 8 BinNode<Elem>* converthelp(char* inlist,int& curr) 9 { 10 if (inlist[curr] == ’/') { 11 curr++; 12 return NULL; 13 } 14 BinNode<Elem>* temp = 15 new BinNode<Elem>(inlist[curr++], NULL, NULL); 16 if (inlist[curr] == ’/') return temp; 17 curr++ // 重要(Eat the internal node mark.) 18 temp->left = converthelp(inlist, curr); 19 temp->right = converthelp(inlist, curr); 20 return temp; 21 }
重要:::注意比较正反代码