码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Unique Binary Search Trees II dfs 深度搜索

时间:2015-01-21 23:56:18      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

Given n, generate all structurally unique BST‘s (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST‘s shown below.

   1         3     3      2      1
    \       /     /      / \           3     2     1      1   3      2
    /     /       \                    2     1         2                 3

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

Hide Tags
 Tree Dynamic Programming
 
  这个嘛,对于1 to n ,如果要用某个值做节点,那么这个值左部分的全部可能的树,递归调用获得,右部分同理,这样便可以获取结果。
 
#include <iostream>
#include <vector>
using namespace std;

/**
 * Definition for binary tree
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    vector<TreeNode *> generateTrees(int n) {
        return help_f(1,n);
    }
    vector<TreeNode *> help_f(int l,int r)
    {
        vector<TreeNode *> ret;
        if(l>r){
            ret.push_back(NULL);
            return ret;
        }
        for(int i=l;i<=r;i++){
            vector<TreeNode *> lPart = help_f(l,i-1);
            vector<TreeNode *> rPart = help_f(i+1,r);
            for(int lidx=0;lidx<lPart.size();lidx++){
                for(int ridx=0;ridx<rPart.size();ridx++){
                    TreeNode * pNode = new TreeNode(i);
                    pNode->left = lPart[lidx];
                    pNode->right = rPart[ridx];
                    ret.push_back(pNode);
                }
            }
        }
        return ret;
    }
};

int main()
{
    return 0;
}

 

[LeetCode] Unique Binary Search Trees II dfs 深度搜索

标签:

原文地址:http://www.cnblogs.com/Azhu/p/4240413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!