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

题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     void convertNode(TreeNode *pNode, TreeNode **pLast){
13         if (pNode == NULL){
14             return;
15         }
16         TreeNode *pCur = pNode;
17         if (pCur->left != NULL){
18             convertNode(pNode->left, pLast);
19         }
20         pCur->left = *pLast;
21         if (*pLast != NULL){
22             (*pLast)->right = pCur;
23         }
24         *pLast = pCur;
25         if (pCur->right != NULL){
26             convertNode(pCur->right, pLast);
27         }
28     }
29     
30     TreeNode* Convert(TreeNode* pRootOfTree)
31     {
32         TreeNode *pLast = NULL;
33         convertNode(pRootOfTree, &pLast);
34         TreeNode *pHead = pLast;
35         
36         while (pHead != NULL && pHead->left != NULL){
37             pHead = pHead->left;
38         }
39         return pHead;
40     }
41 };

 

posted @ 2016-04-05 23:06  早杰  阅读(157)  评论(0编辑  收藏  举报