https://leetcode.com/problems/count-complete-tree-nodes/
计算完全二叉树中的节点个数
完全二叉树当前结点的左右子树至少有一个是满二叉树
// 完全二叉树树的高度为根节点到最左子树的长度
public class Solution {
public int countNodes(TreeNode root) {
// height(root.right) == h - 1表明左子树为满二叉树,再加上root,总共为1 << h,
// height(root.right) == h - 2表明右子树为满二叉树
int h = height(root);
// 位运算全部加括号!!!
return h < 0 ? 0 :
height(root.right) == h - 1 ? (1 << h) + countNodes(root.right) :
(1 << (h - 1)) + countNodes(root.left);
}
private int height(TreeNode root) {
if (root == null) {
return -1;
}
return 1 + height(root.left);
}
}