【LeetCode】95. 不同的二叉搜索树 II(JAVA)(非100%)

原题地址:https://leetcode-cn.com/problems/unique-binary-search-trees-ii/

题目描述:

给定一个整数 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

解题方案:

和96题的思路差不多,只不过改用递归构造树了。刚开始做错的有一点是没有考虑到更改引用指向的内容的问题,需要每次都新申请一个空间,否则下一次循环更改指向内容时上一个也跟着改了。

相关文章:【LeetCode】96. 不同的二叉搜索树(JAVA)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List generateTrees(int n) {
        List tree = new LinkedList();
        if(n == 0)
            return tree;
        tree = rec_Trees(1, n);
        return tree;
    }

    public List rec_Trees(int a, int b) {
        List tree = new LinkedList();
        if(a > b)
            return null;
        else if(a == b)
        {
            TreeNode t = new TreeNode(a);
            tree.add(t);
            return tree;
        }
        else
        {
            for(int k = a; k <= b; k ++)
            {
                //当k为根节点时     
                List lo = rec_Trees(a, k - 1);
                List hi = rec_Trees(k + 1, b);
                if(k == a)
                {
                    for(int j = 0; j < hi.size(); j ++)
                    {
                        TreeNode t = new TreeNode(k);
                        t.right = hi.get(j);
                        tree.add(t);
                    }
                }
                else if(k == b)
                {
                    for(int i = 0; i < lo.size(); i ++)
                    {
                        TreeNode t = new TreeNode(k);
                        t.left = lo.get(i);
                        tree.add(t);
                    }
                }
                else
                {
                    for(int i = 0; i < lo.size(); i ++)
                    {                   
                        for(int j = 0; j < hi.size(); j ++)
                        {
                            TreeNode t = new TreeNode(k);
                            t.left = lo.get(i);
                            t.right = hi.get(j);
                            tree.add(t);
                        }
                    }
                } 
            }
            return tree;
        }
    }
}

 

你可能感兴趣的:(Leetcode)