剑指offer 二叉搜索树与双向链表

题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
 
 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     TreeNode* Convert(TreeNode* pRootOfTree)
13     {
14         TreeNode *pLastNodeInTree = NULL;
15         TreeConvert(pRootOfTree, pLastNodeInTree);
16         TreeNode *pFirstNodeInTree = pLastNodeInTree;
17         while (pFirstNodeInTree != NULL && pFirstNodeInTree->left != NULL) {
18             pFirstNodeInTree = pFirstNodeInTree->left;
19         }
20         return pFirstNodeInTree;
21     }
22     void TreeConvert(TreeNode* pNode, TreeNode* &pLastNodeInTree) {
23         if (pNode == NULL) {
24             return;
25         }
26         TreeNode* pCurrent = pNode;
27         if (pNode->left != NULL) {
28             TreeConvert(pNode->left, pLastNodeInTree);
29         }
30         pCurrent->left = pLastNodeInTree;
31         if (pLastNodeInTree != NULL)
32             pLastNodeInTree->right = pCurrent;
33         pLastNodeInTree = pCurrent;
34         if (pNode->right != NULL) {
35             TreeConvert(pNode->right, pLastNodeInTree);
36         }
37     }
38 };

 

posted @ 2019-08-17 20:00  琴影  阅读(673)  评论(0编辑  收藏  举报