剑指offer27二叉树 转双向链表

来源:互联网 发布:火车头 js内容分页 编辑:程序博客网 时间:2024/05/16 11:30

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。


/*

struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
//将搜索二叉树转变成双向链表(选择的遍历方式为中序遍历,搜索二叉树的中序遍历是排序的)
class Solution {
    //数组转换成双向链表
    void converNode(TreeNode*pNode,TreeNode*(*pLastNodeInList))
        {
        if(pNode==NULL)
            return ;
        if(pNode->left!=NULL)
        converNode(pNode->left,pLastNodeInList);
        //交换指针的部分
        pNode->left=(*pLastNodeInList);
        
        if((*pLastNodeInList)!=NULL)
           (*pLastNodeInList)->right=pNode;
        
           (*pLastNodeInList)=pNode;
        
     if(pNode->right!=NULL)
        converNode(pNode->right,pLastNodeInList);
    }
public:
    TreeNode* Convert(TreeNode* pRootOfTree)
    {
     if(pRootOfTree==NULL)
         return NULL;
      TreeNode*pLastInList=NULL;
      converNode(pRootOfTree,&pLastInList);
      //从链表的头部遍历到链表的尾部
      TreeNode*pHeadInList=pLastInList;
      while(pHeadInList!=NULL&&pHeadInList->left!=NULL)
      pHeadInList=pHeadInList->left;
        
        return pHeadInList;
    } 
};
原创粉丝点击