剑指offer题解(二叉树与双向链表)

题目描述


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

解题思路

中序遍历搜索二叉树,用pre保存中序遍历的前一个节点,cur为当前节点,然后使pre->right=cur,cur->left=pre;

(注意pre要声明为常指针,初始时pre为空),最后从根节点向左遍历,找到头指针。

代码

/*
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==nullptr)
            return nullptr;
        TreeNode *pre=nullptr;
        midV(pRootOfTree,pre);
        TreeNode *res=pRootOfTree;
        while(res->left)
        {
            res=res->left;
        }
        return res;
        
    }
    void midV(TreeNode *cur,TreeNode *& pre)
    {
        if(cur==nullptr)
            return;
        midV(cur->left,pre);
        cur->left=pre;
        if(pre) pre->right=cur;
        pre=cur;
        midV(cur->right,pre);
        
    }
};


 

猜你喜欢

转载自blog.csdn.net/sinat_40766770/article/details/84918083