-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffer_36
31 lines (25 loc) · 918 Bytes
/
offer_36
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//面试题36:二叉搜索树与双向链表
BinaryTreeNode* Convert(BinaryTreeNode* pRootOfTree)
{
BinaryTreeNode* oKastNodeInList=nullptr;
ConverNode(pRootOfTree,&pLastNodeInList);
//pLastNodeInList指向双向链表的尾结点,我们需要返回头结点
BinaryTreeNode* pHeadOfList=pLastNodeInList;
while(pHeadOfList!=nullptr && pHeadOfList->m_pLeft!=nullptr)
pHeadOfList=pHeadOfList->m_pLeft;
return pHeadOfList;
}
void ConvertNode(BinaryTreeNode* pNode,BinaryTreeNode** pLastNodeInList)
{
if(pNode==nullptr)
return;
BinaryTreeNode* pCurrent=pNode;
if(pCurrent->m_pLeft!=nullptr)
ConvertNode(pNode,pLastNodeInList);
pCurrent->m_pLeft=*pLastNodeInList;
if(*pLastNodeInList!=nullptr)
(*pLastNodeInList)->m_pRight=pCurrent;
*pLastNodeInList=pCurrent;
if(pCurrent->m_pRight!=nullptr)
ConvertNode(pCurrent->m_pRight,pLastNodeInList);
}