剑指Offer:26-二叉搜索树与双向链表

题目描述

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

实现

思路

实现1-递归

/*
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)
    {
        //递归退出条件
        if(!pRootOfTree || !pRootOfTree->left && !pRootOfTree->right)
            return pRootOfTree;
        //将左子树转换,并返回链表头节点
        TreeNode* left = Convert(pRootOfTree->left);
        TreeNode* resNode = left;
        //定位到左子树的最后一个节点
        while(left && left->right)
            left = left->right;
        //如果左子树不空的话,追加到pRootOfTree的左边
        if(resNode)
        {
            pRootOfTree->left = left;
            left->right = pRootOfTree;
        }
        //将右子树构成链表
        TreeNode* right = Convert(pRootOfTree->right);
        //右子树追加到根节点右侧
        if(right)
        {
            pRootOfTree->right = right;
            right->left = pRootOfTree;
        }
        return resNode ? resNode : pRootOfTree;
    }
};

实现2-中序遍历

/*
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)
    {
        if(!pRootOfTree || !pRootOfTree->left && !pRootOfTree->right)
            return pRootOfTree;
        TreeNode* pre = nullptr;
        inOrder(pRootOfTree, pre);
        //返回到最头接节点
        TreeNode* res = pRootOfTree;
        while(res->left)
            res = res->left;
        return res;
    }
private:
    void inOrder(TreeNode* cur, TreeNode*& pre)
    {
        if(!cur)
            return ;
        inOrder(cur->left, pre);
        
        //核心代码就是这里,不停的改变两个指针的指向就可以了
        cur->left = pre;
        if(pre)
            pre->right = cur;
        pre = cur;
        
        inOrder(cur->right, pre);
    }
};

你可能感兴趣的:(剑指Offer:26-二叉搜索树与双向链表)