LeetCode095 Unique Binary Search Trees II

详细见:leetcode.com/problems/unique-binary-search-trees-ii


Java Solution: github

package leetcode;

import java.util.ArrayList;

/*
 * 	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
 */

import java.util.LinkedList;
import java.util.List;

import tools.TreeNode辅助.TreeNode;

public class P095_UniqueBinarySearchTreesII {
	public static void main(String[] args) {
		List<TreeNode> ans = new Solution().generateTrees(3);
		for (int i = 0; i < ans.size(); i ++) {
			TreeNode tree = ans.get(i);
			System.out.println(tree.val);
		}
	}
	/*
	 * 	AC
	 * 	3 ms
	 */
	static class Solution {
	    public List<TreeNode> generateTrees(int n) {
	        if (n <= 0) {
	        	return new LinkedList<TreeNode>();
	        }
	        return generateTrees(1, n);
 	    }
	    /*
	     * 	保证arr是排序的
	     */
	    List<TreeNode> generateTrees(int sti, int eni) {
	    	List<TreeNode> this_tree = new ArrayList<TreeNode>();
	    	if (sti > eni) {
	    		this_tree.add(null);
	    		return this_tree;
	    	}
	    	if (sti + 0 == eni) {
	    		TreeNode t0 = new TreeNode(sti);
	    		this_tree.add(t0);
	    		return this_tree;
	    	} else if (sti + 1 == eni) {
	    		// 第一种
	    		TreeNode tree_sti_1 = new TreeNode(sti);
	    		TreeNode tree_eni_1 = new TreeNode(eni);
	    		tree_sti_1.right = tree_eni_1;
	    		this_tree.add(tree_sti_1);
	    		// 第二种
	    		TreeNode tree_sti_2 = new TreeNode(sti);
	    		TreeNode tree_eni_2 = new TreeNode(eni);
	    		tree_eni_2.left = tree_sti_2;
	    		this_tree.add(tree_eni_2);
	    		return this_tree;
	    	}
	    	for (int tra = sti; tra <= eni; tra ++) {
	    		List<TreeNode> this_tree_1 = generateTrees(sti, tra - 1);
	    		List<TreeNode> this_tree_2 = generateTrees(tra + 1, eni);
	    		for (int i_1 = 0; i_1 < this_tree_1.size(); i_1 ++) {
	    			for (int i_2 = 0; i_2 < this_tree_2.size(); i_2 ++) {
	    				TreeNode tree_tra = new TreeNode(tra);
	    				tree_tra.left = this_tree_1.get(i_1);
	    				tree_tra.right = this_tree_2.get(i_2);
	    				this_tree.add(tree_tra);
	    			}
	    		}
	    	}
	    	return this_tree;
	    }
	}
}


C Solution: github

/*
    url: leetcode.com/problems/unique-binary-search-trees-ii
    AC 6ms 100.00%
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct TreeNode stn;
typedef struct TreeNode * ptn;

struct TreeNode {
    int val;
    ptn left;
    ptn right;
};

ptn tn_init(int val) {
    ptn n = (ptn) malloc(sizeof(stn));
    n->left = NULL;
    n->right = NULL;
    n->val = val;
    return n;
}

void tn_free(ptn n) {
    if (n == NULL) return;
    tn_free(n->left);
    tn_free(n->right);
    free(n);
}

typedef ptn T;
typedef struct al sal;
typedef struct al * pal;

struct al {
    int capacity;
    int size;
    T* arr;
};

pal al_init(int capacity) {
    pal l = (pal) malloc(sizeof(sal));
    if (capacity < 1) return NULL;
    l->arr = (T*) malloc(sizeof(T) * capacity);
    l->capacity = capacity;
    l->size = 0;
    return l;
}

void al_expand_capacity(pal l) {
    T* new_arr = (T*) malloc(sizeof(T) * (l->capacity * 2 + 1));
    int i = 0;
    for (i = 0; i < l->capacity; i ++)
        new_arr[i] = l->arr[i];
    free(l->arr);
    l->arr = new_arr;
    l->capacity = l->capacity * 2 + 1;
}

void al_add_last(pal l, T v) {
    if (l->capacity == l->size) al_expand_capacity(l);
    l->arr[l->size] = v;
    l->size ++;
}

T* al_convert_to_array_free_l(pal l) {
    T* arr = l->arr;
    free(l);
    return arr;
}

void al_free(pal l) {
    int i = 0;
    for (i = 0; i < l->size; i ++) {
        if (l->arr[i] != NULL)
            tn_free(l->arr[i]);
    }
    free(l->arr);
    free(l);
}

ptn tn_copy_offset(ptn n, int offset) {
    ptn root = NULL;
    if (n == NULL) return NULL;
    root = tn_init(n->val + offset);
    root->left = tn_copy_offset(n->left, offset);
    root->right = tn_copy_offset(n->right, offset);
    return root;
}

ptn* generateTrees(int n, int* rn) {
    pal* ls = (pal*) malloc(sizeof(pal) * (n+1));
    int i = 0, j = 0, k = 0, t = 0;
    ptn r = NULL, l = NULL, root = NULL, *ans = NULL;
    if (n == 0) {
        *rn = 0;
        return NULL;
    }
    for (i = 0; i <= n; i ++) ls[i] = al_init(16);
    al_add_last(ls[0], (ptn)NULL);
    for (j = 1; j <= n; j ++) {
        for (i = 0; i < j; i ++) {
            for (k = 0; k < ls[i]->size; k ++) {
                l = ls[i]->arr[k];
                for (t = 0; t < ls[j-1-i]->size; t ++) {
                    r = ls[j-1-i]->arr[t];
                    root = tn_init(i+1);
                    root->left = tn_copy_offset(l, 0);
                    root->right = tn_copy_offset(r, i+1);
                    al_add_last(ls[j], root);
                }
            }
        }
    }
    *rn = ls[n]->size;
    ans = (ptn*) malloc(sizeof(ptn) * ls[n]->size);
    for (i = 0; i < ls[n]->size; i ++) ans[i] = ls[n]->arr[i];
    for (i = 0; i <= n; i ++) al_free(ls[i]);
    return ans;
}

int main() {
    int n = 3;
    int rn = 0;
    ptn* a = generateTrees(n, &rn);
    return 0;
}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/unique-binary-search-trees-ii
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年4月24日
    @details:    Solution: 109ms 36.42%
'''

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def clone(self, n, offset):
        if n == None: return None
        c = TreeNode(n.val + offset)
        c.left = self.clone(n.left, offset)
        c.right = self.clone(n.right, offset)
        return c
    
    def generateTrees(self, n):
        """
        :type n: int
        :rtype: List[TreeNode]
        """
        if n < 1: return []
        dp = [[] for i in range(n+1)]
        dp[0].append(None)
        for j in range(1, n+1):
            for i in range(0, j):
                for l in dp[i]:
                    for r in dp[j-1-i]:
                        n = TreeNode(i+1)
                        n.left = l
                        n.right = self.clone(r, i+1)
                        dp[j].append(n)
        return dp[n]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值