Count Complete Tree Nodes
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is
completely filled, and all nodes in the last level are as far left as
possible. It can have between 1 and 2h nodes inclusive at the last level h.
思路
计算根节点的左右子树的高度,如果高度相等则说明是满二叉树,节点数直接使用公式计算:2^h - 1;
否则,对左右孩子递归调用,即countNodes(left) + countNodes(right) + 1.
时间/空间复杂度
最好情况下为满二叉树,时间复杂度为O(h);
最坏情况下为O(n) (?)
程序
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int lh = getLeftHeight(root);
int rh = getRightHeight(root);
if (lh == rh) {
return (1 << lh) - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
private static int getLeftHeight(TreeNode root) {
if (root == null) {
return 0;
}
int count = 0;
while (root != null) {
++count;
root = root.left;
}
return count;
}
private static int getRightHeight(TreeNode root) {
if (root == null) {
return 0;
}
int count = 0;
while (root != null) {
++count;
root = root.right;
}
return count;
}
}

浙公网安备 33010602011771号