二叉搜索树与双向链表,c++
二叉搜索树与双向链表
http://www.nowcoder.com/questionTerminal/947f6eb80d944a84850b0538bf0ec3a5
class Solution { public: TreeNode* Convert(TreeNode* pRootOfTree) { if (pRootOfTree == nullptr) return pRootOfTree; stack<TreeNode*> ista; vector<TreeNode*> ivec; auto pin = pRootOfTree; while (!(ista.empty() && pin == nullptr)){ while(pin != nullptr){ ista.push(pin); pin = pin->left; } if (!ista.empty()){ pin = ista.top(); ista.pop(); ivec.push_back(pin); pin = pin->right; } } ivec.front()->left = nullptr; ivec.back()->right = nullptr; int length = ivec.size(); for (int i = 0; i != length-1; ++i){ ivec[i]->right = ivec[i+1]; ivec[i+1]->left = ivec[i]; } return ivec.front(); } };
写完后看了一下,和不少同学的思路相同
1、二叉搜索树的中序遍历是递增数列,先用非递归方式中序遍历搜索树,节点存在vec容器中
2、按顺序改变个节点的指向
欢迎交流指正!!!