# LeetCode Count Complete Tree Nodes

Description:

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 2hnodes inclusive at the last level h.

Solution:

import java.util.*;

public class Solution {

public int countNodes(TreeNode root) {
if (root == null)
return 0;

int leftH = getLeftHeight(root);
int rightH = getRightHeight(root);

if (leftH == rightH) {
return (1 << leftH) - 1;
} else {

return countNodes(root.left) + countNodes(root.right) + 1;
}
}

int getLeftHeight(TreeNode root) {
TreeNode temp = root;
int len = 0;
while (temp != null) {
temp = temp.left;
len++;
}
return len;
}

int getRightHeight(TreeNode root) {
TreeNode temp = root;
int len = 0;
while (temp != null) {
temp = temp.right;
len++;
}
return len;
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：LeetCode Count Complete Tree Nodes 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)