中序遍历
- 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
1、思路:
二叉搜索树的一大特点就是中序遍历可以将二叉搜索树从小到大排列。需要维护一个变量存放前一个访问到的元素,使该元素的右指针指向当前节点,当前节点的左指针指向该元素。终止条件是到达叶子节点。
Convert
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 }