给定节点数计算完全二叉树的深度

计算完全二叉树的深度

  1. n >= 1 否则返回 0

  2. 给定节点 n 的个数,根据公式:

  3. 代码块

    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();
        }
    
        /**
         * 根据节点数,计算完全二叉树的深度
         * @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);
            }
        }
    
    }
    

你可能感兴趣的:(给定节点数计算完全二叉树的深度)