二叉搜索树与双向链表
Posted Lune-Qiu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉搜索树与双向链表相关的知识,希望对你有一定的参考价值。
我的代码:
1 class Solution { 2 vector<TreeNode*> vec; 3 void OrderTrace(TreeNode* pRoot) 4 { 5 if(!pRoot) return; 6 OrderTrace(pRoot->left); 7 vec.push_back(pRoot); 8 OrderTrace(pRoot->right); 9 } 10 public: 11 TreeNode* Convert(TreeNode* pRootOfTree) 12 { 13 if(!pRootOfTree) 14 return NULL; 15 OrderTrace(pRootOfTree); 16 int length = vec.size(); 17 vec[0]->left = NULL; 18 for(int i = 0; i < length-1; i++) 19 { 20 vec[i]->right = vec[i+1]; 21 vec[i+1]->left = vec[i]; 22 } 23 vec[length - 1]->right = NULL; 24 return vec[0]; 25 } 26 };
示例代码:
class Solution { public: TreeNode* Convert(TreeNode* pRootOfTree) { if(pRootOfTree == nullptr) return nullptr; TreeNode* pre = nullptr; convertHelper(pRootOfTree, pre); TreeNode* res = pRootOfTree; while(res ->left) res = res ->left; return res; } void convertHelper(TreeNode* cur, TreeNode*& pre) { if(cur == nullptr) return; convertHelper(cur ->left, pre); cur ->left = pre; if(pre) pre ->right = cur; pre = cur; convertHelper(cur ->right, pre); } };
以上是关于二叉搜索树与双向链表的主要内容,如果未能解决你的问题,请参考以下文章