IncredibleThings

导航

LeetCode - Unique Binary Search Trees II

Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.

 

Example 1:


Input: n = 3
Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
Example 2:

Input: n = 1
Output: [[1]]
 

Constraints:

1 <= n <= 8
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> res = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            res.addAll(helper(1, n, i));
        }
        return res;
    }
    
    public List<TreeNode> helper(int l, int h, int current) {
        List<TreeNode> res = new ArrayList<>();
        if (l == h && l == current) {
            res.add(new TreeNode(current));
            return res;
        }
        List<TreeNode> left = new ArrayList<>();
        List<TreeNode> right = new ArrayList<>();
        //left
        for (int i = l; i < current; i++) {
            left.addAll(helper(l, current-1, i));
        }
        //right
        for (int i = h; i > current; i--) {
            right.addAll(helper(current+1, h, i));
        }
        if(left.size() == 0) {
            for(int i = 0; i < right.size(); i++) {
                res.add(new TreeNode(current, null, right.get(i)));
            }
            return res;
        }
        
        if (right.size() == 0) {
            for(int i = 0; i < left.size(); i++) {
                res.add(new TreeNode(current, left.get(i), null));
            }
            return res;
        }
        
        for (int i = 0; i < left.size(); i++) {
            for (int j = 0; j < right.size(); j++) {
                res.add(new TreeNode(current, left.get(i), right.get(j)));
            }
        }
        return res;
    }
}

 

posted on 2021-02-20 15:18  IncredibleThings  阅读(36)  评论(0编辑  收藏  举报