二叉搜索树与双向链表
二叉搜索树与双向链表
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
递归版: 树的先中后序的处理就理解成按固定次序处理一个序列, 从大到小, 即中序, 通过指针传回上次递归的值(递归还能这么玩)
class Solution {
public:
void convertNode(TreeNode* pNode, TreeNode **pLastInList) {
if (nullptr == pNode) return;
TreeNode *pCurrent = pNode; // 可以使用pNode来代替pCurrent
if (nullptr != pCurrent->left) {
convertNode(pCurrent->left, pLastInList);
}
pCurrent->left = *pLastInList;
if (nullptr != *pLastInList) {
(*pLastInList)->right = pCurrent;
}
*pLastInList = pCurrent;
if (nullptr != pCurrent->right) {
convertNode(pCurrent->right, pLastInList);
}
}
TreeNode* Convert(TreeNode* pRootOfTree)
{
TreeNode *pLastInList = nullptr;
convertNode(pRootOfTree, &pLastInList);
TreeNode *pHead = pLastInList;
while ((nullptr != pHead) && (nullptr != pHead->left)) {
pHead = pHead->left;
}
return pHead;
}
};
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/