LeetCode每日一题:独一的二叉搜索树 2

问题描述

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

问题分析

和上一题类似,数量也是左子树和右子树的乘积,在递归地过程中用ArrayList来存储node

代码实现

public ArrayList generateTrees(int n) {
        return creatBST2(1, n);
    }

    private ArrayList creatBST2(int low, int high) {
        ArrayList result = new ArrayList<>();
        if (low > high) {
            result.add(null);
            return result;
        }
        for (int i = low; i <= high; i++) {
            ArrayList left = creatBST2(low, i - 1);
            ArrayList right = creatBST2(i + 1, high);
            for (int j = 0; j < left.size(); j++) {
                for (int k = 0; k < right.size(); k++) {//和第一题一样,左子树*右子树
                    TreeNode node = new TreeNode(i);
                    node.left = left.get(j);
                    node.right = right.get(k);
                    result.add(node);
                }
            }
        }
        return result;
    }

你可能感兴趣的:(LeetCode每日一题:独一的二叉搜索树 2)