Different NO.95 binary search tree II

Given an integer n- , all generated by the .... 1  n- node consisting of binary search tree .

Example:

Input: 3
 Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1, null, null, 2],
  [2,1,3],
  [1, zero, two, zero, 3]
]
Explanation:
The output corresponding to the above the following five different binary search tree structure:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    vector<TreeNode*>DFS(int start,int end,map<int,vector<TreeNode*>>&save)
    {
        vector<TreeNode*> ret;
        int pos=start*10+end;
        if(save.find(pos)!=save.end())return save[pos];
        if(start>end)ret.push_back(NULL);
        for(int i=start;i<=end;i++)
        {//i为start 或end的特例在全局会各处理一次
            vector<TreeNode*> left=DFS(start,i-1,save);
            vector<TreeNode*> right=DFS(i+1,end,save);
            for(int j=0;j<left.size();j++)
            {
                for(int k=0;k<right.size();k++)
                {
                    TreeNode* node=new TreeNode(i);
                    node->left=left[j];
                    node->right=right[k];
                    ret.push_back(node);
                }
            }
        }
        save[pos]=ret;
        return ret;
    }

public:
    vector<TreeNode*> generateTrees(int n) {
        map<int,vector<TreeNode*>>save;
        if(n<1)return vector<TreeNode*>();
        else return DFS(1,n,save);
    }
};

When execution: 40 ms, beat the 71.31% of users in Unique Binary Search Trees II submission of C ++

Memory consumption: 12.6 MB, defeated 96.83% of users in Unique Binary Search Trees II submission of C ++

Guess you like

Origin blog.csdn.net/xuyuanwang19931014/article/details/91046065