面試題36:二叉搜尋樹與雙向連結串列
阿新 • • 發佈:2020-08-17
輸入一顆二叉搜尋樹,將該二叉搜尋樹轉換成一個排序的雙向連結串列。
解題思路
這個題目可以使用分治法完成,C++版程式碼如下:
#include <iostream> #include <algorithm> #include <math.h> #include <cstring> #include "ListNode.h" #include "TreeNode.h" #include "Graph.h" using namespace std; #define MAXNUM 100010 #define DRIFT 1001 void ConvertNode(TreeNode* pRoot, TreeNode** pLastNodeInList){ if(pRoot == nullptr) return ; TreeNode* pCurrent = pRoot; if(pCurrent->left != nullptr) ConvertNode(pCurrent->left, pLastNodeInList); pCurrent->left = *pLastNodeInList; if(*pLastNodeInList != nullptr) (*pLastNodeInList)->right = pCurrent; *pLastNodeInList = pCurrent; if(pCurrent->right != nullptr) ConvertNode(pCurrent->right, pLastNodeInList); } TreeNode* Convert(TreeNode* pRootOfTree){ TreeNode* pLastNodeInList = nullptr; ConvertNode(pRootOfTree, &pLastNodeInList); // pLastNodeInList指向雙向連結串列的尾結點 // 我們需要返回頭結點 TreeNode* pHeadOfList = pLastNodeInList; while(pHeadOfList != nullptr && pHeadOfList->left != nullptr) pHeadOfList = pHeadOfList->left; return pHeadOfList; } int main() { return 0; }