满二叉树

题目:对于一颗满二叉树深度为K,节点是为2^K-1;节点值为1至(2^K-1)。给出K和任意三个节点的值,输出包含改三个节点的最小子树的根节点样例输入:4 10 15 13值样例输出:12

思想:满二叉树——有序的

         二分查找,递归

 1 import java.util.Scanner;
 2 
 3 public class Tencent_Main3 {
 4     public static int GG(int left,int right,int a,int b,int c){
 5         int mid=(left+right+1)/2;
 6         if((a<mid)&&(b<mid)&&(c<mid)){
 7             return GG(left,mid-1,a,b,c);
 8         }else if((a>mid)&&(b>mid)&&(c>mid)){
 9             return GG(mid+1,right,a,b,c);
10         }else{
11             return mid;
12         }
13     }
14     
15     public static void SortTree(){
16         Scanner sc=new Scanner(System.in);
17         while(sc.hasNext()){
18             String str=sc.nextLine();
19             String[] array=str.split(" ");
20             
21             int depth=Integer.parseInt(array[0]);
22             int a=Integer.parseInt(array[1]);
23             int b=Integer.parseInt(array[2]);
24             int c=Integer.parseInt(array[3]);
25             
26             int left=1;
27             int right=(int)Math.pow(2, depth)-1;
28             int answer=GG(left,right,a,b,c);
29             System.out.println(answer);
30         }
31     }
32     
33     public static void main(String[] args) {
34         SortTree();
35     }
36 }

 

 1 import java.util.Scanner;
 2 
 3 public class Tencent_Main4 {
 4     public static int GG(int left,int right,int a,int b,int c){
 5         int mid=(left+right)/2;
 6         if((a<mid)&&(b<mid)&&(c<mid)){
 7             return GG(left,mid-1,a,b,c);
 8         }else if((a>mid)&&(b>mid)&&(c>mid)){
 9             return GG(mid+1,right,a,b,c);
10         }else{
11             return mid;
12         }
13     }
14     
15     public static void main(String[] args) {
16         Scanner sc=new Scanner(System.in);
17         while(sc.hasNext()){
18             String str=sc.nextLine();
19             String[] array=str.split(" ");
20             
21             int depth=Integer.parseInt(array[0]);
22             int a=Integer.parseInt(array[1]);
23             int b=Integer.parseInt(array[2]);
24             int c=Integer.parseInt(array[3]);
25             
26             int left=1;
27             int right=(int)Math.pow(2, depth)-1;
28             int answer=GG(left,right,a,b,c);
29             System.out.println(answer);
30         }
31     }
32 }

 

posted @ 2017-04-05 11:16  临江仙zhe  阅读(92)  评论(0)    收藏  举报