根据父节点和子节点下标关系保存x和y到根节点路径看是否有交点
二叉树
https://www.nowcoder.com/practice/5b80ab166efa4551844657603227caeb
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextInt()) { int x = sc.nextInt(); int y = sc.nextInt(); Set<Integer> set = new HashSet<>(); while (x != 0) { set.add(x); x /= 2; } while (y != 0) { if (set.contains(y)) { System.out.println(y); break; } set.add(y); y /= 2; } } } }