码迷,mamicode.com
首页 > 编程语言 > 详细

算法学习——Count Complete Tree Nodes (计算完全二叉树的节点数)

时间:2015-09-07 22:37:44      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

完全二叉树——若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。

解题思路:

满二叉树有一个性质是节点数等于2^h-1(h为高度),所以可以这样判断节点的左右高度是不是一样,如果是一样说明是满二叉树,就可以用公式2^h-1(h为高度),如果左右不相等就递归计算左右节点。

具体代码如下:

/**
* 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) {

int leftDepth = leftDepth(root);
int rightDepth = rightDepth(root);

if (leftDepth == rightDepth)
return (1 << leftDepth) - 1;
else
return 1+countNodes(root.left) + countNodes(root.right);

}

private int rightDepth(TreeNode root) {
// TODO Auto-generated method stub
int dep = 0;
while (root != null) {
root = root.right;
dep++;
}
return dep;
}

private int leftDepth(TreeNode root) {
// TODO Auto-generated method stub
int dep = 0;
while (root != null) {
root = root.left;
dep++;
}
return dep;
}

}

注:上述代码不是自己写的,学习阶段,所以把大神代码拿来学习学习。

算法学习——Count Complete Tree Nodes (计算完全二叉树的节点数)

标签:

原文地址:http://www.cnblogs.com/rlkmxs/p/4789932.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!