`

unique Binary Tree

 
阅读更多

第一种 : 给定一个数值 n 求它能构成的不同的BST的个数:

 这类题,很像那个求斐波那契和,关键就是把状态记录

  通过一个数组 把 1 到 i 的BST数目记录 , : 范围大小相等,那么BST的数目一样,接下来就可以直接利用了!

public class Solution {
    public int numTrees(int n) {
        int[] num = new int[n + 1];
        num[0] = 1;
        
        for (int i = 1 ; i <= n ; i++) { // 1 到i构建BST
            int count = 0;
            for (int j = 1 ; j <= i ; j++) {//哪一个为根节点
                int left  = j - 1; // 左子树的节点个数
                int right = i - j; // 右子树的节点个数
                count += (num[left] * num[right]);
            }
            num[i] = count;
        }
        return num[n];
    }
}

  

 

 

第二种类型 : 要求的不是不同BST的个数,而是把每一棵BST列出来。

  这个题目,开始的时候卡在了右子树该怎么表示那块了!!

 总的来说,这个题目的思路,就是通过一个列表来存储之前数值相对应的子树,只要要表示的数值范围相同,那么子树的形状都是一样,

 比如123 和 456!!!

// 1234  那么当root = 3, left = 2  root = 4 left = 3 ,我想,用一个map把对应的范围内的树存起来,用的时候在来取
    // 比如把 12 的可能情况存起来,求123的BST,root=3的话,就直接可以用12的了?但是一个问题root = 1? 或者 123456 ,root = 3
    // 456怎么办!!这道题目的精华就在这里了!!前面那种解法是没有错的,即通过一个链表来存放各个值对应的树!但要表示456 ,相对应的
    // 就只要把123 的值+3不就等于456了吗!!!! 
     public List<TreeNode> generateTrees(int n) {
        Map<Integer , List<TreeNode>> map = new HashMap<> (); // 每个值对应的树
        List<TreeNode> l = new ArrayList<>();
        // put 0
        l.add(null);
        if(n < 1) return l;
        map.put(0,l); // 0 
        // put 1
        l = new LinkedList<TreeNode>();
        TreeNode root = new TreeNode(1);
        l.add(root);
        map.put(1, l);
        
        for(int i = 2 ; i <= n ; i++) { // 1 到 n  1234567
            List<TreeNode> list = new ArrayList<>();
            // TreeNode node = new TreeNode(i); // 加入 i = 7
            for(int j = 1 ; j <= i ; j++) { // 1到i中哪一个值为顶点
                List<TreeNode> left = map.get(j - 1); // 6 5 4 3 2 1 0
                List<TreeNode> right = map.get(i - j); //0 1 2 3 4 5 6
                for (TreeNode ln : left) {
                    for (TreeNode rn : right) {  
                        TreeNode node = new TreeNode(j); //注意这一块,你不能在上面那个for循环定义TreeNode ,或者更上层,因为这里每一个treeNode对应着的就是一颗新的树
                             node.left = ln;                  // 你如果在外层循环中定义,这不会乱套了吗。
                             node.right = copyToRight(rn , j); //右子树的节点 就需要把左子树中相同数目的子树 的 节点 + add! 
                        list.add(node);
                    }
                }
            }
            map.put(i , list);
        }
        return map.get(n);
    }
    
    // 只要节点的数目相同,那么他们子树形状都是一样,我们接下来要的就是遍历树,对每个节点 val + add
    public TreeNode copyToRight(TreeNode node , int add) {
        if(node == null) return node;
        TreeNode n = new TreeNode (node.val + add);
        n.left = copyToRight(node.left , add);
        n.right = copyToRight(node.right , add);
        return n;
    }
    
}

 

分享到:
评论

相关推荐

    陈越、何钦铭-数据结构作业11:Tree Traversals Again二叉树非递归遍历/栈遍历

    An inorder binary tree traversal ... Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.

    陈越、何钦铭-数据结构作业16:Complete Binary Search Tree完全二叉搜索树

    Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal ...

    cpp-算法精粹

    Construct Binary Tree from Inorder and Postorder Traversal 二叉查找树 Unique Binary Search Trees Unique Binary Search Trees II Validate Binary Search Tree Convert Sorted Array to Binary Search Tree ...

    CBST.rar_The Keys_bst

    Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal ...

    CSMA/CA MAC Protocol with Function of Monitoring based on Binary Tree Conflict Resolution for Cognitive Radio Networks

    Due to the unique characteristics and related needs of the cognitive radio networks, design .their network protocol is a critical task. For its characteristics, design and implement a comprehensive ....

    leetcode添加元素使和等于-Leetcode-tree:力码树

    Leetcode-tree 94题 Binary Tree Inorder Traversal 对于树的问题,大多数我们都会使用递归的方法。原因是树的左子树也是树,右子树也是树,使用递归的方法最简单快捷。这道题是需要我们用Inorder的顺序输出节点。in...

    LeetCode最全代码

    * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search]...

    gasstationleetcode-leetcode:LeetcodeOJ解决方案

    加油站 leetcode 【演示记录】 报告 展示 2017/03/06 1.二和,167....2107/03/06 15.3 总和,16.3 ...总和,11....62.Unique ...63.Unique ...Binary Search Tree, 120.Triangle, 139.Word Break, 152.Maximum Produ

    leetcode分类-LeetCode:力码

    leetcode 分类 LeetCode Progress 128/154 Other Solutions C++,有详细思路解释 python,部分有解释 Java,部分有解释 ...norvig神牛Python代码写的很飘逸,果然是有LISP内功的人!...Unique ...Binary Tree Binar

    leetcode答案-leetcode:leetcode

    Binary Tree 这?也太简单了吧。。一行代码,一个尾递归搞定啊。。 终于想清楚了,leetcode的AC率应该是:在线编辑、肉眼检查,提交的准确率!借助线下debug工具,有何难度可言?丝毫没有模拟在线面试的味道了。。...

    word源码java-LintCode:代码

    Unique Permutations Combination Sum Letter Combination of a Photo Number Palindrome Par 第一节课内容结束,题目训练. 详情 Binary Search Tree (二叉查找树) 第二次课, Binary Search Tree T(n) = O(1) + T( ...

    STL 源码剖析(侯捷先生译著)

    5.1.2 平衡二元搜寻树(balanced binary search tree) 203 5.1.3 AVL tree(Adelson-Velskii-Landis tree) 203 5.1.4 单旋转(Single Rotation) 205 5.1.5 双旋转(Double Rotation) 206 5.2 RB-tree(红黑...

    STL源码剖析.pdg

    5.1.2 平衡二元搜寻树(balanced binary search tree) 203 5.1.3 avl tree(adelson-velskii-landis tree) 203 5.1.4 单旋转(single rotation) 205 5.1.5 双旋转(double rotation) 206 5.2 rb-tree(红黑...

    Everyday Data Structures

    Get acquainted with the tree structures such as heap, binary, and graphs, apply them to work Unleash the power of different sorting techniques such as bubble sort, quick sort, merge sort, insertion ...

    python3.6.5参考手册 chm

    Updated module: ElementTree 1.3 Build and C API Changes Capsules Port-Specific Changes: Windows Port-Specific Changes: Mac OS X Port-Specific Changes: FreeBSD Other Changes and Fixes Porting to ...

    EhLib 8.0 Build 8.0.023 Pro Edition FullSource for D7-XE8

    Has interface for requesting list of all unique values in one column of records array, ignoring local filter of the DataSet. TDBGridEh uses this property for automatic filling a list in ...

    EhLib 6.3 Build 6.3.176 Russian version. Full source included.

    Has interface for requesting list of all unique values in one column of records array, ignoring local filter of the DataSet. TDBGridEh uses this property for automatic filling a list in ...

    ehlib_vcl_src_9_3.26

    Has interface for requesting list of all unique values in one column of records array, ignoring local filter of the DataSet. TDBGridEh uses this property for automatic filling a list in ...

Global site tag (gtag.js) - Google Analytics