您的位置:首页 > Web前端 > Node.js

leetcode--Count Complete Tree Nodes

2015-08-01 20:21 549 查看
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.

题意:给定一棵完全二叉树,计算节点数目。

分类:二叉树

解法1:完全二叉树的定义是,除最后一层外,每一层上的节点数均达到最大值;在最后一层上只缺少右边的若干结点。

完全二叉树的一个特殊例子是满二叉树。

如果一棵树是满二叉树,那么我们可以用公式2^k-1计算它的节点数目。

如果不是满二叉树,我们要分别计算左子树和右子树,这是一个递归过程,最好左右子树和+1,为结果

根据上面的说法,我们可以先通过查找最左边节点的个数,最右边节点的个数

如果这两个数目相同,就是满二叉树,可以通过公式直接返回

如果不同,则递归分别计算左右子树的数目

/**
* 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 left = getLeft(root.left)+1;
int right = getRight(root.right)+1;
if(left==right){//如果左右相等,就是满二叉树
return (2<<(left-1))-1;
}else{//如果左右不等,分别递归计算
return countNodes(root.left)+countNodes(root.right)+1;
}
}

/**
* 获得最左边节点的数目
*/
int getLeft(TreeNode root){
int left = 0;
while(root!=null){
left++;
root = root.left;
}
return left;
}

/**
* 获得最右边节点的数目
int getRight(TreeNode root){
int right = 0;
while(root!=null){
right++;
root = root.right;
}
return right;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息