题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
二叉树的遍历如下图所示:箭头指向左下表示递进,箭头指向右上表示回归
例如
先序遍历:先遍历当前节点,即对当前节点执行某种操作,然后向左子树递进,从左子树回归,再向右子树递进,最后从右子树回归
中序遍历:从左子树回归后,再遍历当前节点,然后向右子树递进,最后从右子树回归
后序遍历:向左子树递进,从左子树回归,向右子树递进,从右子树回归,遍历当前节点,即执行某种操作
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
//参考《剑指offer》
TreeNode* Convert(TreeNode* pRootOfTree)
{
if(pRootOfTree == nullptr)
return nullptr;
TreeNode* pLastNodeInList = nullptr;
Convert(pRootOfTree, pLastNodeInList);
TreeNode* pNode = pLastNodeInList;
while(pNode->left != nullptr){
pNode = pNode->left;
}
return pNode;
}
void Convert(TreeNode* pRootOfTree, TreeNode* &pLastNodeInList){
if(pRootOfTree == nullptr)
return;
Convert(pRootOfTree->left, pLastNodeInList);
pRootOfTree->left = pLastNodeInList;
if(pLastNodeInList != nullptr)
pLastNodeInList->right = pRootOfTree;
pLastNodeInList = pRootOfTree;
Convert(pRootOfTree->right, pLastNodeInList);
}
};