【1】题目
题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。比如输入图4.12中左边的二叉搜索树,则输出转换之后的排序双向链表。
【2】思路
注:根结点、左子树和右子树。在把左、右子树都转换成排序的双向链表之后再和根结点链接起来,整棵二叉搜索树也就转换成了排序的双向链表。按照中序遍历的顺序,当我们遍历转换到根结点(值为10的结点)时,它的左子树已经转换成一个排序的链表了,并且处在链表中的最后一个结点是当前值最大的结点。我们把值为 8 的结点和根结点链接起来,此时链表中的最后一个结点就是10了。接着我们去遍历转换右子树,并把根结点和右子树中最小的结点链接起来。至于怎么去转换它的左子树和右子树,由于遍历和转换过程是一样的,我们很自然地想到可以用递归。
【3】代码
#pragma once
#ifndef TRANSLATENODE_H
#define TRANSLATENODE_H
struct BinaryTreeNode
{
int m_nvalue;
BinaryTreeNode * m_pLeft;
BinaryTreeNode * m_pRight;
};
class TranslateNode
{
public:
TranslateNode();
~TranslateNode();
BinaryTreeNode * Convert(BinaryTreeNode *pRootOfTree);
void ConvertNode(BinaryTreeNode *pNode, BinaryTreeNode * *pLastNodeInList);
};
#endif // !TRANSLATENODE_H
#include "pch.h"
#include "TranslateNode.h"
TranslateNode::TranslateNode()
{
}
TranslateNode::~TranslateNode()
{
}
//*指针,**指向指针的指针
void TranslateNode::ConvertNode(BinaryTreeNode * pNode, BinaryTreeNode * *pLastNodeInList)
{
if (pNode==nullptr)
{
return;
}
BinaryTreeNode *pCurrent = pNode;
if (pCurrent->m_pLeft!=nullptr)
{
ConvertNode(pCurrent->m_pLeft, pLastNodeInList);
}
pCurrent->m_pLeft = *pLastNodeInList;
if (*pLastNodeInList!=nullptr)
{
(*pLastNodeInList)->m_pRight = pCurrent;
}
*pLastNodeInList = pCurrent;
if (pCurrent->m_pRight !=nullptr)
{
ConvertNode(pCurrent->m_pRight, pLastNodeInList);
}
}
BinaryTreeNode * TranslateNode:: Convert(BinaryTreeNode *pRootOfTree)
{
BinaryTreeNode *pLastNodeInList = nullptr;
ConvertNode(pRootOfTree, &pLastNodeInList);
BinaryTreeNode *pHeadOfList = pLastNodeInList;
while (pHeadOfList!=nullptr && pHeadOfList->m_pLeft!=nullptr)
{
pHeadOfList = pHeadOfList->m_pLeft;
}
return pLastNodeInList;
}