Sword refers to offer (C++)-JZ36: binary search tree and doubly linked list (data structure - tree)

Author: Steven Zhai
Copyright Notice: The copyright belongs to the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source

Topic description:

Input a binary search tree, convert the binary search tree into a sorted doubly linked list. As shown below

Data range: The number of nodes in the input binary tree is 0≤n≤1000, and the value of each node in the binary tree is 0≤val≤1000.
Requirements: space complexity O(1) (that is, operating on the original tree), time complexity O(n)

Notice:

1. It is required that no new nodes can be created, and only the point of the node pointer in the tree can be adjusted. After the transformation is completed, the left pointer of the node in the tree needs to point to the predecessor, and the right pointer of the node in the tree needs to point to the successor

2. Returns the pointer to the first node in the linked list

3. The TreeNode returned by the function has left and right pointers, which can actually be regarded as a data structure of a doubly linked list

4. You do not need to output a doubly linked list, the program will automatically print the output according to your return value

Example:

enter:

{10,6,14,4,8,12,16}

return value:

From left to right are:4,6,8,10,12,14,16;From right to left are:16,14,12,10,8,6,4;

illustrate:

Input the binary tree in the problem map, and return the head node of the doubly linked list when outputting.

Problem solving ideas:

This question examines the use of data structure trees. Use in-order traversal to store the nodes of the binary tree in a vector, and then build a doubly linked list in turn.

Test code:

/*
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 pRootOfTree;
        stack<TreeNode*> s;
        vector<TreeNode*> v;
        auto a=pRootOfTree;
        // 中序遍历
        while(!(s.empty()&&a==nullptr))
        {
            while(a!=nullptr)
            {
                s.push(a);
                a=a->left;
            }
            if(!s.empty())
            {
                a=s.top();
                s.pop();
                v.push_back(a);
                a=a->right;
            }
        }
        // 双向链表建立
        v.front()->left=nullptr;
        v.back()->right=nullptr;
        int size=v.size();
        for(int i=0;i<size-1;++i)
        {
            v[i]->right=v[i+1];
            v[i+1]->left=v[i];
        }
        return v.front();
    }
};

Guess you like

Origin blog.csdn.net/zhaitianbao/article/details/123610707