不同的二叉树查找II

来源:互联网 发布:讨鬼传2捏脸数据女 编辑:程序博客网 时间:2024/06/05 15:01
给出n,生成所有由1...n为节点组成的不同的二叉查找树
样例
给出n = 3,生成所有5种不同形态的二叉查找树:


1         3     3       2    1
 \       /     /       / \    \
  3     2     1       1   3    2
 /     /       \                \

2     1         2                3


import java.util.ArrayList;import java.util.List;import java.util.Scanner;/** *  * 给出n,生成所有由1...n为节点组成的不同的二叉查找树样例给出n = 3,生成所有5种不同形态的二叉查找树:1         3     3       2    1 \       /     /       / \    \  3     2     1       1   3    2 /     /       \                \2     1         2                3 * @author Dell * */public class Test164 {  public static List<TreeNode> generateTrees(int n)  {  if(n<0) return null;  return createTree(1,n);    }  public static List<TreeNode> createTree(int start, int end)  {  List<TreeNode> res=new ArrayList<>();  if(start>end)  {  res.add(null);    return res;  }  for(int i=start;i<=end;i++)  {  List<TreeNode> left=createTree(start,i-1);  List<TreeNode> right=createTree(i+1,end);  for(int j=0;j<left.size();j++)  {  for(int k=0;k<right.size();k++)  {  TreeNode root=new TreeNode(i);  root.left=left.get(j);  root.right=right.get(k);  res.add(root);  }    }    }  return res;  }public static void main(String[] args) {   Scanner sc=new Scanner(System.in);   int n=sc.nextInt();   List<TreeNode> list=null;    list=generateTrees(n);        System.out.println(list);}}


原创粉丝点击