計算完全二叉樹的深度
n >= 1否則返回0給定節(jié)點 n 的個數(shù),根據(jù)公式:
-
代碼塊
import java.util.Scanner; public class Shendu { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int nodeNum = sc.nextInt(); shendu(nodeNum); sc.close(); } /** * 根據(jù)節(jié)點數(shù),計算完全二叉樹的深度 * @param nodeNum */ public static void shendu(int nodeNum) { if (nodeNum >= 1) { // 使用換底公式 int deep = (int)((Math.log(nodeNum)) / (Math.log(2))) + 1; // 向下取整 + 1 System.out.println(deep); } else { System.out.println(0); } } }