import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head TreeNode类
     * @return int整型
     */
    public int nodeNum (TreeNode head) {
        // write code here
        if (head == null)return 0;
        TreeNode left = head.left;
        TreeNode right = head.right;
        int leftCnt = 0; // 左子树深度
        while (left != null) {
            leftCnt++;
            left = left.left;
        }
        int rightCnt = 0;
        while (right != null) {
            rightCnt++;
            right = right.right;
        }
        // 左右子树深度相同,是满二叉树,总节点个数 = 2^height - 1
        // 但是高度从0开始,即根节点高度为0,所以要使用移位运算
        if(leftCnt == rightCnt)return (2 << leftCnt) - 1;
        return 1 + nodeNum(head.left) + nodeNum(head.right);
    }
}

利用满二叉树的性质