zoukankan      html  css  js  c++  java
  • [LeetCode] 95. 不同的二叉搜索树 II ☆☆☆(递归,n个数组成的所有二叉搜索树)

     https://leetcode-cn.com/problems/unique-binary-search-trees-ii/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-2-7/

    描述

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

    示例:

    解析

    利用一下查找二叉树的性质。左子树的所有值小于根节点,右子树的所有值大于根节点。

    所以如果求 1...n 的所有可能。

    我们只需要把 1 作为根节点,[ ] 空作为左子树,[ 2 ... n ] 的所有可能作为右子树。

    2 作为根节点,[ 1 ] 作为左子树,[ 3...n ] 的所有可能作为右子树。

    3 作为根节点,[ 1 2 ] 的所有可能作为左子树,[ 4 ... n ] 的所有可能作为右子树,然后左子树和右子树两两组合。

    4 作为根节点,[ 1 2 3 ] 的所有可能作为左子树,[ 5 ... n ] 的所有可能作为右子树,然后左子树和右子树两两组合。

    ...

    n 作为根节点,[ 1... n ] 的所有可能作为左子树,[ ] 作为右子树。

    至于,[ 2 ... n ] 的所有可能以及 [ 4 ... n ] 以及其他情况的所有可能,可以利用上边的方法,把每个数字作为根节点,然后把所有可能的左子树和右子树组合起来即可。

    如果只有一个数字,那么所有可能就是一种情况,把该数字作为一棵树。而如果是 [ ],那就返回 null。

    代码

    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> ans = new ArrayList<TreeNode>();
        if (n == 0) {
            return ans;
        }
        return getAns(1, n);
    
    }
    
    private List<TreeNode> getAns(int start, int end) { 
        List<TreeNode> ans = new ArrayList<TreeNode>();
        //此时没有数字,将 null 加入结果中
        if (start > end) {
            ans.add(null);
            return ans;
        }
        //只有一个数字,当前数字作为一棵树加入结果中
        if (start == end) {
            TreeNode tree = new TreeNode(start);
            ans.add(tree);
            return ans;
        }
        //尝试每个数字作为根节点
        for (int i = start; i <= end; i++) {
            //得到所有可能的左子树
            List<TreeNode> leftTrees = getAns(start, i - 1);
             //得到所有可能的右子树
            List<TreeNode> rightTrees = getAns(i + 1, end);
            //左子树右子树两两组合
            for (TreeNode leftTree : leftTrees) {
                for (TreeNode rightTree : rightTrees) {
                    TreeNode root = new TreeNode(i);
                    root.left = leftTree;
                    root.right = rightTree;
                    //加入到最终结果中
                    ans.add(root);
                }
            }
        }
        return ans;
    }
  • 相关阅读:
    ip报文
    常见端口
    navicat15 破解版
    谷歌跨域设置
    CSS flex弹性布局来做 页面底部自适应:页面高度不足时,在底部显示;页面高度超出时,随页面滚动(亲测有效)
    phpstorm 2019 激活码
    aes cbc模式
    Vue的安装及使用快速入门
    从SVN服务器端彻底删除错误提交版本
    Nginx配置https和wss
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/11425189.html
Copyright © 2011-2022 走看看