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

题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
 1 class Solution {
 2 public:
 3     TreeNode* Convert(TreeNode* pRootOfTree)
 4     {
 5         if(pRootOfTree == nullptr) return nullptr;
 6         TreeNode* pre = nullptr;
 7          
 8         convertHelper(pRootOfTree, pre);
 9          
10         TreeNode* res = pRootOfTree;
11         while(res ->left)
12             res = res ->left;
13         return res;
14     }
15      
16     void convertHelper(TreeNode* cur, TreeNode*& pre)
17     {
18         if(cur == nullptr) return;
19          
20         convertHelper(cur ->left, pre);
21          
22         cur ->left = pre;
23         if(pre) pre ->right = cur;
24         pre = cur;
25          
26         convertHelper(cur ->right, pre);
27          
28          
29          
30     }
31 };

 

 
 1 class Solution {
 2 public:
 3     TreeNode* head=NULL,*tail=NULL;
 4     void inorder(TreeNode* p)
 5     {
 6         if(p!= NULL)
 7         {
 8             inorder(p->left);
 9             if(head==NULL)
10             {
11                 head = p;
12                 tail = p;
13             }
14             else
15             {
16                 p->left = tail;
17                 tail->right = p;
18                 tail = p;
19             }
20             inorder(p->right);
21              
22         }
23     }  
24     TreeNode* Convert(TreeNode* pRootOfTree)
25     {
26         if(pRootOfTree==NULL)
27             return NULL;
28          inorder(pRootOfTree);
29         return head;
30     }
31 };

 

posted @ 2019-05-21 22:51  unique_ptr  阅读(315)  评论(0编辑  收藏  举报