【问题标题】:Generating All Binary Search Trees from 1 to n生成从 1 到 n 的所有二叉搜索树
【发布时间】:2019-06-29 21:47:08
【问题描述】:

我遇到了以下问题:

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

例如,给定 3,得到:

                                  

我正在做以下事情:

Generate all the permutations of the sequence (1, 2, ..., n).
For each permutation p:
    Create a tree t.
    For each number n in p:
        Insert n into t.
    If t has not yet been generated, keep it. <-- Expensive Operation

但是,这种方法很慢,因为会生成重复的树(对于 n = 3,(2, 1, 3) 和 (2, 3, 1) 生成相同的树),我需要确保它们不会被保留.有人会指出我更快的方法吗?

【问题讨论】:

  • 你可以在stackoverflow.com/questions/16004723/…987654321@这个问题的答案中找到有效的算法
  • Enumerate search trees的可能重复
  • @ile 我认为 OP 想把它们都打印出来而不是计算它们
  • 那里描述了一个简单的映射,可以高效地枚举它们。
  • @ile 刚看到很抱歉没看到那部分。

标签: algorithm


【解决方案1】:

这是没有重复的伪代码(但是你仍然需要很多空间,因为树生成的数量不多)。

TreeList void genAllBST(int high,int low) {

  if(high>=low) {
      currList = []
      for(int i=low;i<=high;i++) {
          curr = new Node(i);
          leftList = genAllBST(i-1,low);
          rightList = genAllBST(high,i+1);
          TreeList c = connect(curr,leftList,rightList);  
          currList.add(c);
      }

     return(currList);

  }

   return(null);
}

genAllBST(n,1);

【讨论】:

  • 您能否定义“TreeList”、“ConnectedList”和“connect”?谢谢。
  • @ScottOdle TreeList 是指向其根的树的列表,ConnectedList 应该是 TreeList 抱歉,connect 函数使所有可能的树以 curr 作为根,一棵来自 leftList 作为左子树,一棵来自 rightList作为右子树
猜你喜欢
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
  • 2018-02-20
  • 2023-03-08
相关资源
最近更新 更多