zoukankan      html  css  js  c++  java
  • 腾讯实习笔试编程题 满二叉搜索树求三个节点的最低公共祖先

    题目

    对于一棵满二叉搜索树深度为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 }
  • 相关阅读:
    HUST 1372 marshmallow
    HUST 1371 Emergency relief
    CodeForces 629D Babaei and Birthday Cake
    CodeForces 629C Famil Door and Brackets
    ZOJ 3872 Beauty of Array
    ZOJ 3870 Team Formation
    HDU 5631 Rikka with Graph
    HDU 5630 Rikka with Chess
    CodeForces 626D Jerry's Protest
    【POJ 1964】 City Game
  • 原文地址:https://www.cnblogs.com/deadend/p/6663736.html
Copyright © 2011-2022 走看看