简述:采用先序遍历,找到叶子结点,按照题目要求尾插法即可。
typedef struct BiTree{
struct BiTree* lchild;
struct BiTree* rchild;
int data;
}BiTree;
BiTree* head;
BiTree* pre;
//pre指向前驱,目的主要是为了head始终指向头指针,使得head可以用于输出遍历。
//要求该算法把二叉树的叶子结点按从左到右的顺序连成一个单链表,表头指针为head
void leavesToLine(BiTree* tree,BiTree* &head){
if (tree == NULL) {
return;
}
if (tree->lchild == NULL && tree->rchild == NULL) {
cout<<"data:"<<tree->data<<endl;
if (head == NULL) {
head = tree;
pre = head;
}else{
pre->rchild = tree;
pre = pre->rchild;
}
}
leavesToLine(tree->lchild, head);
leavesToLine(tree->rchild, head);
}