Programmer Interview Golden Code-Interview Questions 04.09. Binary Search Tree Sequence

1. Topic introduction

Traverse an array from left to right, and gradually generate a binary search tree by continuously inserting elements into the tree. Given a binary search tree composed of different nodes, output all possible arrays of this tree.

 

Example:
Given the following binary tree

        2
       / \
      1 3
return:

[
   [2,1,3],
   [2,3,1]
]

Source: LeetCode
Link: https://leetcode-cn.com/problems/bst-sequences-lcci
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

       This question is equivalent to investigating the full arrangement in disguise, and the method used is "backtracking + recursion + double-ended queue". This method has not been figured out by myself, and I can learn from others, and record it here.

Three, problem-solving code

class Solution {
public:
    vector<vector<int>> BSTSequences(TreeNode* root) {
        vector<vector<int>> res;
        if(!root)
            return {
   
   {}};
        vector<int> ans;
        deque<TreeNode*> q;
        q.push_back(root);
        dfs(ans, res, q);
        return res;
    }

    void dfs(vector<int>& ans, vector<vector<int>> &res, deque<TreeNode*>& q)
    {
        if(q.empty())
        {
            res.push_back(ans);
            return;
        }
        for(int i = q.size(); i > 0; --i)
        {
            TreeNode* cur = q.front();
            q.pop_front();
            ans.push_back(cur->val);
            int count = 0;
            if(cur->left)
            {
                q.push_back(cur->left);
                ++count;
            }
            if(cur->right)
            {
                q.push_back(cur->right);
                ++count;
            }
            dfs(ans, res, q);
            for(int j = 0; j < count; ++j)
                q.pop_back();
            
            ans.pop_back();
            q.push_back(cur);
        }
    }
};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/108143175