注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
- class Solution {
-
- K = 最後一排滿打滿算的全部元素個數D = 樹的層數
-
- // O(lgK * D) ??????
-
- public int countNodes(TreeNode root) {
-
- if(root == null) return 0;
- int depth = countDepth(root);
- // 找到最後一層的所有位置(滿打滿算)
- int left = 0;
- int right = (int) Math.pow(2, depth - 1) - 1;
-
- while (left + 1 < right) {
- int mid = left + (right - left) / 2;
- if ( exist(mid, depth, root) ) {
- left = mid;
- } else{
-
- right = mid;
- }
-
- }
-
- if( exist(right, depth, root ) ) {
-
- return (int) Math.pow(2, depth - 1) + right;
-
- } else {
-
- return (int) Math.pow(2, depth - 1) + left;
- }
- }
-
- // Count the tree depth
- public int countDepth(TreeNode root){
-
- if(root == null) return 0;
-
- if(root.left == null) return 1;
-
- return countDepth(root.left) + 1;
- }
-
- // see if it is exist
- public boolean exist(int Target, int D, TreeNode node){
-
- int L = 0;
-
- int R = (int) Math.pow(2, D - 1) - 1;
-
- // 用L和R是否重疊來判斷,是否到達最後一層
- while( L < R) {
-
- int mid2 = L + (R - L)/2;
-
- if( Target <= mid2 ) {
-
- R = mid2 ;
- node = node.left;
- }
-
- if( Target > mid2 ) {
- L = mid2 + 1;
- node = node.right;
- }
- }
-
-
- /* 用層數來判斷是否到達最後一層
- int currentLevel = 1;
-
- while( currentLevel < D) {
- int mid2 = L + (R - L)/2;
- if( Target > mid2 ) {
- L = mid2;
- node = node.right;
- }
- if( Target <= mid2 ) {
- R = mid2;
- node = node.left;
- }
- currentLevel++;
- }
- */
-
- return node != null;
- }
- }
复制代码
這個雙層 binary search 的解法,速度上pk掉所有其他解法。但我算不出他的時間複雜度。
求大神賜教!
我已陣亡。
|