[剑指 offer] JT26---Binary search tree and doubly linked list (after pondering for a few days, it is quite an abstract question)

The twenty-sixth question of the sword refers to the offer

The topic is as follows

Enter a binary search tree and convert the binary search tree into a sorted doubly linked list. It is required that no new nodes can be created, but only the point of the node pointer in the tree can be adjusted.
What a simple question, but it hurts me so deeply!

The idea and code are as follows

Now my personal understanding is relatively superficial, it is the middle order traversal
. After the analysis of the recursive structure, I will update it.
After all, this question has been stuck for a few days, so I will write it out first.

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

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114794645