二叉搜索樹轉化雙向鏈表

題目:輸入一棵二叉搜索樹,將該二叉搜索樹轉換成一個排序的雙向鏈表


要求排序可以想到中序遍歷,把根節點的左右子樹都轉換成排序好的雙向鏈表,再將根節點左子樹的最大值,右子樹的最小值與根節點相連。

class Solution {
public:
    TreeNode* Convert(TreeNode* pRootOfTree)
    {
        TreeNode *lastnode=NULL;
        convertnode(pRootOfTree,lastnode);
        TreeNode *headnode=lastnode;
        while(headnode!=NULL&&headnode->left!=NULL)
            headnode=headnode->left;
        return headnode;
    }
    void convertnode(TreeNode* pnode,TreeNode* &plastnode){
        if(pnode==NULL)
        return ;
        TreeNode *pcurrent=pnode;
        if(pcurrent->left!=NULL)
            convertnode(pcurrent->left,plastnode);
        pcurrent->left=plastnode;
        if(plastnode!=NULL)
            (plastnode)->right=pcurrent;
        plastnode=pcurrent;
        if(pcurrent->right!=NULL)
            convertnode(pcurrent->right,plastnode);
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章