# [leetcode]Count Complete Tree Nodes

149人阅读 评论(0)

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;
}
public void addCount(){
this.res++;
}
public int getCount(){
return this.res;
}
public int countNodes(TreeNode root) {
if(root == null) return 0;
addCount();
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;
}
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：23570次
• 积分：1023
• 等级：
• 排名：千里之外
• 原创：80篇
• 转载：23篇
• 译文：0篇
• 评论：2条
文章分类
阅读排行
最新评论