二叉树转换为链表

一、问题描述
输入一棵二叉搜索树,现在要将该二叉搜索树转换成一个排序的双向链表。而且在转换的过程中,不能创建任何新的结点,只能调整树中的结点指针的指向来实现。

查阅了相关内容,基本了解了这个问题的解析方法与思想。
DList BSTreeToList(BSTree tree)
{
    if(tree == NULL)
        return NULL;
    //找到最左边的结点,即转换后链表的头结点
    DLNode *head = FindLeftmostNode(tree);
    BSNode *last_node = NULL;
    //进行转换
    ConvertNode(tree, &last_node);
    return head;
}
BSNode* FindLeftmostNode(BSTree tree)
{
    if(tree == NULL)
        return NULL;
    while(tree->left != NULL)
        tree = tree->left;
    return tree;
}
void ConvertNode(BSTree tree, BSNode **last_node)
{
    if(tree == NULL)
        return;
    //对tree的左子树进行转换,last_node是转换后链表最后一个结点的指针
    if(tree->left != NULL)
        ConvertNode(tree->left, last_node);
    //调整tree的left指针,指向上一个结点
    tree->left = *last_node;
    //调整指向最后一个结点,right指向下一个结点
    if(*last_node != NULL)
        (*last_node)->right = tree;
    //调整指向最后链表一个结点的指针
    *last_node = tree;
    //对tree的右子树进行转换,last_node是转换后链表最后一个结点的指针
    if(tree->right != NULL)
        ConvertNode(tree->right, last_node);
}




搜索二叉树转换成链表

//搜索二叉树->双链表
void BinaryTreeToDoublyList(BiTree &root)
{
	if (root == NULL)
		return;

	if (root->lChild == NULL && root->rChild == NULL)
		return;

	BiNode* left = root->lChild;
	BiNode* right = root->rChild;
	BinaryTreeToDoublyList(left);
	BinaryTreeToDoublyList(right);

	//找到左子树的最大结点
	if(left)
	{
		while(left->rChild)
		{
			left = left->rChild;
		}

		left->rChild = root;
		root->lChild = left;
	}

	if (right)
	{
		//找到右子树的最大结点
		while(right->lChild)
		{
			right = right->lChild;
		}

		right->lChild = root;
		root->rChild = right;
	}
}

void BinaryTreeToDoublyListMain(BiTree &root)
{
	if (root == NULL)
		return;

	BinaryTreeToDoublyList(root);

	//root指向双向链表头
	if (root->lChild)
		root = root->lChild;
}


二叉搜索树与双向链表

void Convert(BinaryTreeNode* pNode,BinaryTreeNode** pLastNodeInList)
{
    if(pNode==NULL)
        return;

    BinaryTreeNode* pCurrent=pNode;
    //左子树转换,遍历到左子树的叶子结点
    if(pCurrent->m_pLeft!=NULL)//遍历左子树
        Convert(pCurrent->m_pLeft,pLastNodeInList);

    pCurrent->m_pLeft=*pLastNodeInList;
    if((*pLastNodeInList)!=NULL)
        (*pLastNodeInList)->m_pRight=pCurrent;

    *pLastNodeInList=pCurrent;
    //右子树转换
    if(pCurrent->m_pRight!=NULL)//遍历右子树
        Convert(pCurrent->m_pRight,pLastNodeInList);

}

BinaryTreeNode* Convert(BinaryTreeNode* pRoot)
{
    BinaryTreeNode* pLastNodeInList=NULL;//指向双向链表的尾结点
    Convert(pRoot,&pLastNodeInList);//转换排序二叉树为双向链表

    //求双向链表的头结点
    BinaryTreeNode* pHeadOfList=pLastNodeInList;
    while(pHeadOfList!=NULL&&pHeadOfList->m_pLeft!=NULL)
        pHeadOfList=pHeadOfList->m_pLeft;
    return pHeadOfList;

}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值