26叉搜索树与双向链表
1 //二叉搜索树与双向链表 2 //题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。 3 struct TreeNode 4 { 5 int val; 6 struct TreeNode* left; 7 struct TreeNode* right; 8 TreeNode(int x):val(x), left(NULL),right(NULL) 9 { 10 11 } 12 }; 13 class Solution 14 { 15 public: 16 TreeNode* Convert(TreeNode* pRootOfTree) 17 { 18 TreeNode* pDListNodeLast = NULL;//指向双向链表的尾结点 19 ConvertNode(pRootOfTree, &pDListNodeLast); 20 21 // pDListNodeLast指向双向链表的尾结点 22 //我们需要返回头结点 23 TreeNode* pHeadOfList = pDListNodeLast; 24 while(pHeadOfList != NULL && pHeadOfList->left != NULL) 25 { 26 pHeadOfList = pHeadOfList->left; 27 } 28 return pHeadOfList; 29 30 } 31 private: 32 void ConvertNode(TreeNode* pRootOfTree, TreeNode **pDListNodeLast) 33 { 34 if (pRootOfTree == NULL ) 35 { 36 return; 37 } 38 TreeNode* currentNode = pRootOfTree; 39 //转换和遍历的过程是一样的。采用递归。此处采用的是中序遍历 40 41 //先访问左子树的叶子结点 42 if (currentNode->left != NULL) 43 { 44 ConvertNode(currentNode->left, pDListNodeLast); 45 } 46 //进行处理-叶子结点的左指针指向其父节点 47 currentNode->left = *pDListNodeLast; 48 if (*pDListNodeLast != NULL) 49 { 50 //父节点的右指针指向叶子结点 51 (*pDListNodeLast)->right = currentNode; 52 } 53 //转换完成后,则将遍历过的结点放到*pDListNodeLast指向的链表中 54 *pDListNodeLast = currentNode; 55 56 //然后再处理右边的叶子结点, 57 if (currentNode->right!= NULL) 58 { 59 ConvertNode(currentNode->right, pDListNodeLast); 60 } 61 } 62 };
在代码的世界尽情的翱翔吧!