题目
对于一棵满二叉搜索树深度为K,节点数为2^k - 1,节点值为[1, 2^k - 1]。给出k和任意三个节点的值,输出包含该三个节点的最小子树的根节点值。
输入: 4 10 15 13
输出:12
思路
二分搜索,当搜索到节点x时,若x为三个节点之一或三个节点不在以x为根节点的树的子树的同一侧,则当前节点即为所求。否则二分
代码
1 import java.util.Scanner; 2 3 4 public class Main { 5 6 public static int binarySearch(int a,int b,int c, int left, int right) { 7 int m = left + (right - left) / 2; 8 9 if((a - m) * (b - m) <= 0 || (a - m) * (c - m) <= 0 || (c - m) * (b - m) <= 0) { 10 return m; 11 } else if(a > m) { 12 return binarySearch(a, b, c, m + 1, right); 13 } else { 14 return binarySearch(a, b, c, left, m - 1); 15 } 16 } 17 18 public static void main(String[] args) { 19 Scanner sc = new Scanner(System.in); 20 int k = sc.nextInt(); 21 int a = sc.nextInt(); 22 int b = sc.nextInt(); 23 int c = sc.nextInt(); 24 System.out.println(binarySearch(a, b, c, 1, (2 << k) - 1)); 25 } 26 }