95. 不同的二叉搜索树 II (Java)

给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树 。

 

示例:

输入:3
输出:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:

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

提示:

0 <= 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) {
        return generateSubTrees(1,n);
    }

    public List<TreeNode> generateSubTrees(int start, int end) {
        if(start == end) {
            List<TreeNode> rootList = new ArrayList<>();
            TreeNode node = new TreeNode (start);
            rootList.add(node);
            return rootList;
        }
        
        List<TreeNode> rootList = new ArrayList<>();
        for (int mid = start; mid <= end; mid++){
            List<TreeNode> leftList = new ArrayList<>();
            List<TreeNode> rightList = new ArrayList<>();
            if(mid > start) leftList = generateSubTrees(start, mid-1);
            if(mid < end) rightList = generateSubTrees(mid+1, end);
            
            //只有左子树的情况
            if(rightList.isEmpty()) {
                for(int i = 0; i < leftList.size(); i++){
                    TreeNode root = new TreeNode(mid, leftList.get(i), null);
                    rootList.add(root);
                }
            }
            //只有右子树的情况
            else if(leftList.isEmpty()) {
                for(int j = 0; j < rightList.size(); j++){
                    TreeNode root = new TreeNode(mid, null, rightList.get(j));
                    rootList.add(root);
                }
            }
            //左右子树都有的情况
            else {
                for(int i = 0; i < leftList.size(); i++) {
                    for(int j = 0; j < rightList.size(); j++){
                        TreeNode root = new TreeNode(mid, leftList.get(i), rightList.get(j));
                        rootList.add(root);
                    }
                }
            }  
        }
        return rootList;
    }
}

 

posted on 2020-07-04 14:27  joannae  阅读(241)  评论(0编辑  收藏  举报

导航