求完全二叉树的节点个数,有两种做法,第一种是当成二叉树一个一个求节点个数;第二种是求左右子树的高度,因为已知是完全二叉树,所以到最后必然是左右子树高度一致
完全二叉树的节点个数
// (https://leetcode-cn.com/problems/count-complete-tree-nodes/
class Solution {
public int countNodes(TreeNode root) {
TreeNode left = root, right = root;
int leftCount = 0, rightCount = 0;
while (left != null) {
left = left.left;
leftCount ++;
}
while (right != null) {
right = right.right;
rightCount ++;
}
if (leftCount == rightCount) {
return (int)Math.pow(2, leftCount) - 1;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
Reference:
- https://labuladong.gitee.io/algo/