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

【leetcode】Count Complete Tree Nodes (Java)

2015-12-02 00:00 621 查看

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 2hnodes inclusive at the last level h.
题意就是求完全二叉树的节点个数。

解题思路:

这道题比较简单,要利用完全二叉树的性质简化过程:即如果当树的左右节点的高度是相同时,就是一个满二叉树,就可以得到他的节点数为(2^height - 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 rightLevel = countRightLevel(root);
int leftLevel = countLeftLevel(root);

if(rightLevel == leftLevel)
return (1 << leftLevel) - 1;
return countNodes(root.left) + 1 + countNodes(root.right);
}
public int countRightLevel(TreeNode root){
int level = 0;
TreeNode temp = root;
while(temp != null){
level++;
temp = temp.right;
}
return level;
}
public int countLeftLevel(TreeNode root){
int level = 0;
TreeNode temp = root;
while(temp != null){
level++;
temp = temp.left;
}
return level;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java