zoukankan      html  css  js  c++  java
  • LeetCode——Unique Binary Search Trees II

    Question

    Given an integer 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
    

    Solution

    分治的思想,分别求出1~n个节点为根节点构成的BST.

    例如 k, 1<= k <= n; 为根节点的问题可以划分为,左子树和右子树,左子树中的节点值为1k-1,然后1k-1分别为根节点,同理右子树。右子树中的节点值为k+1n,然后k+1n分别为根节点,以此类推。

    Code

    /**
     * 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 {
    public:
        vector<TreeNode*> generateTrees(int n) {
            if (n <= 0)
                return vector<TreeNode*>();
            else
                return generateSubTree(1, n);
        }
        vector<TreeNode*> generateSubTree(int s, int e) {
            vector<TreeNode*> res;
            if (s > e) {
                res.push_back(NULL);
                return res;
            }
            for (int i = s; i <= e; i++) {
                vector<TreeNode*> left = generateSubTree(s, i - 1);
                vector<TreeNode*> right = generateSubTree(i + 1, e);
                
                // 所有组合 = size(left) * size(right)
                for (TreeNode* p : left) {
                    for (TreeNode* q : right) {
                        struct TreeNode* root = new TreeNode(i);
                        root->left = p;
                        root->right = q;
                        res.push_back(root);
                    }
                }
            }
            return res;
        }
    };
    
  • 相关阅读:
    Linux Shell 编程
    Linux下压缩与解压
    rsync实现文件备份同步
    linux中ulimit作用
    3dmax卡通渲染插件pencil+渲染线框
    世嘉开发部部长:这3点能提升游戏留存率
    消息中间件 分布式
    高并发高性能
    你的系统如何支撑高并发
    分布式系统的阿喀琉斯之踵:数据一致性
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7515492.html
Copyright © 2011-2022 走看看