題目:輸入一棵二元查找樹,將該二元查找樹轉換成一個排序的雙向鏈表。
要求不能建立任何新的結點,只調整指針的指向。
10
/ /
6 14
/ / / /
4 8 12 16
轉換成雙向鏈表
4=6=8=10=12=14=16。
node
首先咱們定義的二元查找樹 節點的數據結構以下:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};ios
思路:中序排列簡歷二元查找樹;中序遍歷二元查找樹,在遍歷過程當中,轉換成雙鏈表。數據結構
代碼:spa
#include <stdio.h> #include <iostream> using namespace std; struct BSTreeNode { int m_nValue; // value of node BSTreeNode *m_pLeft; // left child of node BSTreeNode *m_pRight; // right child of node }; typedef BSTreeNode DoubleList; DoubleList * pHead; DoubleList * pListIndex; void convertToDoubleList(BSTreeNode * pCurrent); // 建立二元查找樹 void addBSTreeNode(BSTreeNode * & pCurrent, int value) { if (NULL == pCurrent) { BSTreeNode * pBSTree = new BSTreeNode(); pBSTree->m_pLeft = NULL; pBSTree->m_pRight = NULL; pBSTree->m_nValue = value; pCurrent = pBSTree; } else { if ((pCurrent->m_nValue) > value) { addBSTreeNode(pCurrent->m_pLeft, value); } else if ((pCurrent->m_nValue) < value) { addBSTreeNode(pCurrent->m_pRight, value); } else { cout<<"重複加入節點"<<endl; } } } // 遍歷二元查找樹 中序 void ergodicBSTree(BSTreeNode * pCurrent) { if (NULL == pCurrent) { return; } if (NULL != pCurrent->m_pLeft) { ergodicBSTree(pCurrent->m_pLeft); } // 節點接到鏈表尾部 convertToDoubleList(pCurrent); // 右子樹爲空 if (NULL != pCurrent->m_pRight) { ergodicBSTree(pCurrent->m_pRight); } } // 二叉樹轉換成list void convertToDoubleList(BSTreeNode * pCurrent) { pCurrent->m_pLeft = pListIndex; if (NULL != pListIndex) { pListIndex->m_pRight = pCurrent; } else { pHead = pCurrent; } pListIndex = pCurrent; cout<<pCurrent->m_nValue<<endl; } int main() { BSTreeNode * pRoot = NULL; pListIndex = NULL; pHead = NULL; addBSTreeNode(pRoot, 10); addBSTreeNode(pRoot, 4); addBSTreeNode(pRoot, 6); addBSTreeNode(pRoot, 8); addBSTreeNode(pRoot, 12); addBSTreeNode(pRoot, 14); addBSTreeNode(pRoot, 15); addBSTreeNode(pRoot, 16); ergodicBSTree(pRoot); getchar(); return 0; }