标签:表头 init 描述 text 理解 roo space 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 void CovertNode(TreeNode *root,TreeNode **pLastNodeInitList) 13 { 14 if(root == NULL) 15 return; 16 TreeNode *pCurrent = root; 17 if(pCurrent->left) 18 { 19 CovertNode(pCurrent->left,pLastNodeInitList); 20 } 21 pCurrent->left = *pLastNodeInitList; 22 if(*pLastNodeInitList != NULL) 23 (*pLastNodeInitList)->right = pCurrent; 24 *pLastNodeInitList = pCurrent; 25 if(pCurrent->right != NULL) 26 { 27 CovertNode(pCurrent->right,pLastNodeInitList); 28 } 29 } 30 TreeNode* Convert(TreeNode* pRootOfTree) 31 { 32 TreeNode *pLastNodeInitList = NULL; 33 CovertNode(pRootOfTree,&pLastNodeInitList); 34 //pLastNodeInitLast指向链表的最后一个结点 35 TreeNode *pHead = pLastNodeInitList; 36 while(pHead != NULL && pHead->left != NULL) 37 { 38 pHead = pHead->left; 39 } 40 return pHead; 41 } 42 };
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 //非递归中序遍历 13 void midorder2(TreeNode* root,vector<TreeNode *> *v){ 14 if(root==NULL) 15 return; 16 stack<TreeNode *> s; 17 while(root||!s.empty()) 18 { 19 while(root) 20 { 21 s.push(root); 22 root=root->left; 23 } 24 root=s.top(); 25 s.pop(); 26 (*v).push_back(root); 27 root=root->right; 28 } 29 } 30 TreeNode* Convert(TreeNode* pRootOfTree) 31 { 32 if(pRootOfTree == NULL) 33 return NULL; 34 vector<TreeNode *> v; 35 midorder2(pRootOfTree,&v); 36 37 int n = v.size(); 38 39 v[0]->left = NULL; 40 for(int i=1;i<n;i++) 41 { 42 v[i-1]->right = v[i]; 43 v[i]->left = v[i-1]; 44 } 45 v[n-1]->right = NULL; 46 return v[0]; 47 } 48 };
标签:表头 init 描述 text 理解 roo space offer 方法
原文地址:http://www.cnblogs.com/qqky/p/6917461.html