Sword refers to Offer 36. Binary search tree and doubly linked list (inspect the in-order traversal, need to store the previous node)

Thursday, March 11, 2021, the weather is fine [Do not lament the past, do not waste the present, do not fear the future]


1. Introduction

Sword refers to Offer 36. Binary search tree and doubly linked list
Insert picture description here

2. Problem solution (inspect the in-order traversal, need to store the previous node)

The middle order traverses each node and stores the previous node at the same time to complete the construction of the doubly linked list.

2.1 Recursion

class Solution {
    
    
public:
    Node* pre, *head;
    Node* treeToDoublyList(Node* root) {
    
    
        if(root==nullptr) return nullptr;
        dfs(root);

		// 要求是双向循环链表,所以接上头和尾
        head->left = pre;
        pre->right = head;
        return head;
    }

    void dfs(Node* cur){
    
    
        if(cur==nullptr) return;
        dfs(cur->left);

		// 核心操作在这里
        if(pre!=nullptr) pre->right = cur;
        else head = cur;
        cur->left = pre;
        pre = cur;

        dfs(cur->right);
    }
};

2.2 Iteration

class Solution {
    
    
public:
    Node* treeToDoublyList(Node* root) {
    
    
        if(root==nullptr) return root;
        stack<Node*> st;
        Node* cur = root, *pre = nullptr, *head = nullptr;
        while(cur || !st.empty()){
    
    
            if(cur){
    
    
                st.push(cur);
                cur = cur->left;
            }
            else{
    
    
                cur = st.top();
                st.pop();
                if(pre!=nullptr) pre->right = cur;
                else head = cur;
                cur->left = pre;
                pre = cur;

                cur = cur->right;
            }
        }
        head->left = pre;
        pre->right = head;
        return head;
    }
};

references

"Sword Finger Offer Second Edition"

Guess you like

Origin blog.csdn.net/m0_37433111/article/details/114681004