/*
这题目一看就是要递归 不能创建新节点
这到题目应该是我做这本书目前位置 最卡的一道题了。。想了好久。
但也怪自己浮躁把。
主要思想convert函数 main汉斯调用的函数 主要就是创建last变量 然后 最后返回头指针
convertnode 是重要的其实主要过程可以理解未一次中序遍历bst 得到有序的序列并且联系
每次输入一个指针 先把左边的弄好 然后last记录了左边的最后 再把last和根连接
然后last变成根 继续中序右子数 先到最左再和last连起来
*/
#include<iostream>
#include<cstdio>
using namespace std;
struct BinaryTreeNode
{
int data;
BinaryTreeNode * leftchild;
BinaryTreeNode * rightchild;
BinaryTreeNode(int t):data(t){};
};
BinaryTreeNode * CreateTree()
{
BinaryTreeNode * root=new BinaryTreeNode(10);
root->leftchild=new BinaryTreeNode(6);
root->rightchild=new BinaryTreeNode(14);
BinaryTreeNode * tmp=root->leftchild;
tmp->leftchild=new BinaryTreeNode(4);
tmp->rightchild=new BinaryTreeNode(8);
tmp=root->rightchild;
tmp->leftchild=new BinaryTreeNode(12);
tmp->rightchild=new BinaryTreeNode(16);
return root;
}
//这个递归函数完成整个链表的创建
/*
先左再中 后右 链接起来就行 用lastnode 记录 目前最后一个节点 然后后面再和这个链接
就是这样的思想
*/
void ConvertNode(BinaryTreeNode * root,BinaryTreeNode **lastnode)
{
if(root==NULL) return ;
BinaryTreeNode * p=root;
if(p->leftchild!=NULL)
ConvertNode(p->leftchild,lastnode);
p->leftchild=*lastnode;
if(*lastnode!=NULL)
(*lastnode)->rightchild=p;
*lastnode=p;
if(p->rightchild!=NULL)
ConvertNode(p->rightchild,lastnode);
}
BinaryTreeNode * Convert(BinaryTreeNode * root)
{
BinaryTreeNode * last=NULL;
ConvertNode(root,&last);
//返回头指针
BinaryTreeNode * head=last;
while(head!=NULL && head->leftchild !=NULL)
head=head->leftchild;
return head;
}
void PrintList(BinaryTreeNode * head)
{
while(head!=NULL)
{
printf("%d ",head->data);
head=head->rightchild;
}
}
int main()
{
BinaryTreeNode * root=CreateTree();
BinaryTreeNode * linklist=Convert(root);
PrintList(linklist);
return 0;
}
剑指offer面试题27BST转换为有序双向链表
最新推荐文章于 2021-03-20 18:36:00 发布