剑指offer 27:二叉搜索树与双向链表
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
解题思路
采用中序遍历遍历二叉树,利用二叉排序树的特性,顺次连接节点,形成双向链表。
C++代码实现
/* 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; ConvertNode(pRootOfTree ,&pLastNodeInList); TreeNode * pHeadFirst=pLastNodeInList; //记录根节点的值 while(pHeadFirst!=NULL && pHeadFirst->left!=NULL){ pHeadFirst=pHeadFirst->left; } return pHeadFirst; } void ConvertNode(TreeNode* pRootOfTree ,TreeNode** pLastNodeInlist){ if (pRootOfTree ==NULL){ return ; } TreeNode * cur=pRootOfTree; if (cur->left!=NULL){ ConvertNode(cur->left,pLastNodeInlist); } cur->left=*pLastNodeInlist; if(*pLastNodeInlist!=NULL){ (*pLastNodeInlist)->right=cur; } (*pLastNodeInlist)=cur; if (cur->right!=NULL){ ConvertNode(cur->right,pLastNodeInlist); } } };