@(labuladong的算法小抄)[完全二叉树]
leetcode 222. 完全二叉树的节点个数
题目描述
解题思路
参考:labuladong的算法小抄P243
如果是普通二叉树,可以直接用递归做,但这题是完全二叉树,所以可以利用特性做。
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
TreeNode l = root, r = root;
/* 记录左右子树的高度 */
int hl = 0, hr = 0;
while (l != null) {
l = l.left;
hl++;
}
while (r != null) {
r = r.right;
hr++;
}
/* 如果左右子树高度相同,说明是一棵满二叉树 */
if (hl == hr) {
return (int)Math.pow(2, hl) - 1;
}
/* 如果左右子树高度不同,则按照普通二叉树的逻辑计算 */
return 1 + countNodes(root.left) + countNodes(root.right);
}
}