面试题27:二叉搜索树与双向链表

这题逻辑比较难:

把左子树中最大的节点,根节点,右子树中最小的节点链接起来;

需要用pLastNodeInList来标记上一个节点

注意这里pLastNodeInList用的是BinaryTreeNode**

 1 BinaryTreeNode* Convert(BinaryTreeNode* pRootOfTree)
 2 {
 3     BinaryTreeNode *pLastNodeInList = NULL;
 4     ConvertNode(pRootOfTree, &pLastNodeInList);
 5 
 6     // pLastNodeInList指向双向链表的尾结点,
 7     // 我们需要返回头结点
 8     BinaryTreeNode *pHeadOfList = pLastNodeInList;
 9     while(pHeadOfList != NULL && pHeadOfList->m_pLeft != NULL)
10         pHeadOfList = pHeadOfList->m_pLeft;
11 
12     return pHeadOfList;
13 }
14 
15 void ConvertNode(BinaryTreeNode* pNode, BinaryTreeNode** pLastNodeInList)
16 {
17     if(pNode == NULL)
18         return;
19 
20     BinaryTreeNode *pCurrent = pNode;
21 
22     if (pCurrent->m_pLeft != NULL)
23         ConvertNode(pCurrent->m_pLeft, pLastNodeInList);
24 
25     pCurrent->m_pLeft = *pLastNodeInList; 
26     if(*pLastNodeInList != NULL)
27         (*pLastNodeInList)->m_pRight = pCurrent;
28 
29     *pLastNodeInList = pCurrent;
30 
31     if (pCurrent->m_pRight != NULL)
32         ConvertNode(pCurrent->m_pRight, pLastNodeInList);
33 }

 

posted on 2016-07-08 13:49  已停更  阅读(222)  评论(0编辑  收藏  举报