Question
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
Solution
-
因为树的每个节点都有两个指针,并且双向链表的节点也有两个指针,所以这个转换是可行的。
-
首先是有序的链表,并且是二叉搜索树,那么我们可以想到用中序遍历
-
左指针指向链表的前一个节点,右指针指向链表的下一个节点,其中需要一个指针指向链表的最后一个节点。
Code
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree) {
// 记录链表中的最后一个节点
TreeNode* pLastNodeInList = NULL;
ConvertCore(pRootOfTree, &pLastNodeInList);
while (pLastNodeInList != NULL && pLastNodeInList->left != NULL)
pLastNodeInList = pLastNodeInList->left;
return pLastNodeInList;
}
void ConvertCore(TreeNode* pNode, TreeNode** pLastNodeInList) {
if (pNode == NULL)
return;
// 正在被访问的节点
TreeNode* pCurrent = pNode;
if (pCurrent->left != NULL) {
ConvertCore(pCurrent->left, pLastNodeInList);
}
pCurrent->left = *pLastNodeInList;
if (*pLastNodeInList != NULL)
(*pLastNodeInList)->right = pCurrent;
*pLastNodeInList = pCurrent;
if (pCurrent->right != NULL)
ConvertCore(pCurrent->right, pLastNodeInList);
}
};