日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LintCode刷题——不同的二叉查找树I、II

發布時間:2025/3/20 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LintCode刷题——不同的二叉查找树I、II 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

不同的二叉查找樹I:

題目內容:

給出 n,問由 1...n 為節點組成的不同的二叉查找樹有多少種?

樣例:

給出n = 3,有5種不同形態的二叉查找樹:

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

算法分析:

先來看一下二叉查找樹的特點,當選定一個節點i作為中間節點時:

  ①位于該節點左子樹中的所有節點均小于i,假設該節點的左子樹的排列情況有m種;

  ②位于該節點右子樹中的所有節點均大于i,假設該節點的右子樹的排列情況有n種;

  ③綜合①和②,當節點i作為當前二叉查找樹的首節點時,該二叉查找樹的總排列數目有m*n;

因此對于一個擁有n個節點的二叉查找樹,其每一個節點均能成為某一二叉查找樹的首節點,因此動態規劃的表達式為:

  DP[i] = sum{ DP[j-1] * DP[i-j] },其中1=< j <=i,DP[i]表示i個節點所能組成的二叉查找樹的數目;

代碼: 

public int numTrees(int n) {// write your code hereif(n==0)return 1;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++){int left=result[j-1];int right=result[i-j];result[i]+=left*right;}}return result[n];}

不同的二叉查找樹II:

題目內容:

給出n,生成所有由1...n為節點組成的不同的二叉查找樹;

樣例:

給出n = 3,有5種不同形態的二叉查找樹:

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

算法分析:

本題在 I 的基礎上要求返回的不是組數而是具體的組合,很明顯本題需要用遞歸的方式來解決問題,和 I 的思想基本一致,在遞歸的過程中找出所有的左右子樹的排列組合,然后分別連接到當前節點的左子樹和右子樹,將結果作為當前層的二叉查找樹的所有排列組合進行返回。

代碼:

HashMap<String,List<TreeNode>> map = new HashMap<>();public List<TreeNode> findSolution(int begin, int end){List<TreeNode> result = new ArrayList<>();if(begin>end){result.add(null);return result;}if(begin==end){TreeNode temp = new TreeNode(begin);result.add(temp);return result;}String tag = String.valueOf(begin)+"-"+String.valueOf(end);if(map.get(tag)!=null){return map.get(tag);}for(int i=begin;i<=end;i++){List<TreeNode> left = findSolution(begin,i-1);List<TreeNode> right = findSolution(i+1,end);if(left.size()!=0&&right.size()!=0){for(TreeNode t1:left){for(TreeNode t2:right){TreeNode temp = new TreeNode(i);temp.left = t1;temp.right=t2;result.add(temp);}}}if(left.size()!=0&&right.size()==0){for(TreeNode t1:left){TreeNode temp = new TreeNode(i);temp.left = t1;result.add(temp);}}if(left.size()==0&&right.size()!=0){for(TreeNode t2:right){TreeNode temp = new TreeNode(i);temp.right = t2;result.add(temp);}}}map.put(tag,result);return result;}public List<TreeNode> generateTrees(int n) {// write your code heremap = new HashMap<>();return findSolution(1,n);/*long startTime=System.nanoTime();List<TreeNode> result = findSolution(1,n);long endTime=System.nanoTime();System.out.println("運行時間為:"+(endTime-startTime));return result;*/}

代碼中我還建立了一個map作為中間結果的記錄,用來降低一些重復區間段求解的時間開銷,其效果還是很明顯的,當n=11時,沒有map的算法時間開銷為124313992ns,而有map的算法時間開銷為82106610ns;但是這題我我試了下即使不用map也能夠AC;

?

?

?

?

?

?

?

轉載于:https://www.cnblogs.com/Revenent-Blog/p/7568627.html

總結

以上是生活随笔為你收集整理的LintCode刷题——不同的二叉查找树I、II的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。