• LeetCode-096-不同的二叉搜索树


    不同的二叉搜索树

    题目描述:给你一个整数 n ,求恰由 n 个节点组成且节点值从 1n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。

    二叉搜索树(Binary Search Tree):又称二叉排序树,它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。

    示例说明请见LeetCode官网。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/unique-binary-search-trees/
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解法一:递归法
    • 首先,当n为0的时候,结果是一棵空树,直接返回空的list。
    • 当n大于0的时候,使用递归的方法来分别获取左右子树,递归过程如下:
      • 所有节点都可以作为根节点,也就是遍历从1到n的所有值作为根节点,当前根节点为i;
      • 然后i左边的所有的值递归调用方法作为i的左子树;
      • i右边的所有的值递归调用方法作为i的右子树;
      • 最后把根节点i和相应的左右子树拼成一棵树,放到结果集中。
    • 最后,返回结果集的size值即为符合条件的二叉搜索树的种数。

    说明:该方法参照的 LeetCode-095-不同的二叉搜索树 II,不过在提交的时候超时了。

    解法一:规律

    找规律可知,当整数为n时,二叉搜索数的结果是前面所有可能的结果之和。

    import com.kaesar.leetcode.TreeNode;
    import java.util.ArrayList;
    import java.util.List;
    
    public class LeetCode_096 {
        /**
         * 递归:该方法运行时超时了
         *
         * @param n
         * @return
         */
        public static int numTrees(int n) {
            // 当n为0的时候,是一棵空树
            if (n == 0) {
                return 1;
            }
            return generateTrees(1, n).size();
        }
    
        private static List<TreeNode> generateTrees(int start, int end) {
            List<TreeNode> allTrees = new ArrayList<>();
            if (start > end) {
                allTrees.add(null);
                return allTrees;
            }
            for (int i = start; i <= end; i++) {
                // 所有可能的左子树集合
                List<TreeNode> leftTrees = generateTrees(start, i - 1);
    
                // 所有可能的右子树集合
                List<TreeNode> rightTrees = generateTrees(i + 1, end);
    
                for (TreeNode leftTree : leftTrees) {
                    for (TreeNode rightTree : rightTrees) {
                        TreeNode root = new TreeNode(i);
                        root.left = leftTree;
                        root.right = rightTree;
                        allTrees.add(root);
                    }
                }
            }
            return allTrees;
        }
        
        public static int numTrees2(int n) {
            int[] result = new int[n + 1];
            result[0] = 1;
            result[1] = 1;
            for (int i = 2; i <= n; i++) {
                for (int j = 1; j <= i; j++) {
                    result[i] += result[j - 1] * result[i - j];
                }
            }
            return result[n];
        }
    
        public static void main(String[] args) {
            System.out.println(numTrees(3));
            System.out.println(numTrees2(3));
        }
    }
    

    【每日寄语】 年轻是本钱,但不努力就不值钱。

  • 相关阅读:
    C计算double能精确到多少位
    C计算int最大值、最小值
    AndroidStudio右键new无activity
    java替换特殊字符串 $
    lamda表达式排序
    docker toolbox 设置镜像加速
    tomcat优化
    nginx配置相关
    SQL 优化
    elasticsearch 概念初识
  • 原文地址:https://www.cnblogs.com/kaesar/p/15527293.html
Copyright © 2020-2023  润新知