# [leetcode]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.

public class Solution {
public int res;
Solution(){
this.res = 0;
}
this.res++;
}
public int getCount(){
return this.res;
}
public int countNodes(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null)
return getCount();
if(root.left != null){
countNodes(root.left);
}
if(root.right != null)
countNodes(root.right);
return getCount();
}
}


public class Solution {
public int res;
Solution(){
this.res = 0;
}
public int getLeftHeight(TreeNode root){
int height = 0;
while(root.left != null) {
root = root.left;
height ++;
}
return height;
}
public int getRightHeight(TreeNode root){
int height = 0;
while(root.right != null) {
root = root.right;
height ++;
}
return height;
}
public int countNodes(TreeNode root) {
if(root == null) return 0;
int lheight = getLeftHeight(root);
int rheight = getRightHeight(root);
if(lheight == rheight) return (2 << lheight) - 1;
else return countNodes(root.left) + countNodes(root.right) + 1;
}
}

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

## Leetcode[222]-Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.Definition of a complete binary tree from Wi...
• Dream_angel_Z
• 2015年06月11日 13:24
• 1508

## leetcode 222: Count Complete Tree Nodes

leetcode 222: Count Complete Tree Nodes c++ java python
• xudli
• 2015年06月06日 05:14
• 14227

## LeetCode222:Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from W...
• u012501459
• 2015年07月29日 17:17
• 836

## LeetCode222 Count CompleteTree Nodes(计算完全二叉树的节点数) Java 题解

• u012249528
• 2015年07月09日 20:51
• 1216

## Count Complete Tree Nodes -- leetcode

Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from ...
• elton_xiao
• 2015年09月10日 15:36
• 275

## [LeetCode]Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from ...
• CiaoLiang
• 2015年06月06日 20:57
• 1130

## [LeetCode] Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.Definition of a complete binary tree from Wi...
• u011331383
• 2015年06月06日 13:45
• 1417

## Leetcode Count Complete Tree Nodes

Leetcode Count Complete Tree Nodes，本算法主要可以使用二分搜索加速计算出最后一层最右边缺少的结点数，通过二分法，计算量变为O(h * h)，其中h为树高，相对递归等方...
• u010842603
• 2015年12月08日 11:58
• 279

## leetcode Count Complete Tree Nodes

• eshaoliu
• 2015年06月16日 20:34
• 289

## 【Leetcode】Count Complete Tree Nodes

• yeqiuzs
• 2015年11月24日 15:19
• 356

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