LeetCode——Count Complete Tree Nodes
Description:
Given a complete binary tree, count the number of nodes.
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.
思路:给一颗完全二叉树求其节点的个数。首先要明确完全二叉树的定义:把满二叉树从上到下,从左到右进行编号,完全二叉树是其中编号没有断续的部分。也就是说完全二叉树只可能在最右子树的叶子节点的位子上有空缺。而且左右子树的高度差不能大于1。所以只要是count(左节点)==count(右节点)那么就是一颗满二叉树。可以用公式计算出节点的个数NodeCount=2^h - 1。若不是满二叉树的话就递归遍历求count(左子树) + count(右子树) + 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;
TreeNode left = root, right = root;
int leftCount = 0;
while(left!= null) {
left = left.left;
leftCount ++;
}
int rightCount = 0;
while(right != null) {
right = right.right;
rightCount ++;
}
if(leftCount==rightCount) {
return (2<<(leftCount-1)) - 1;
} else {
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
}
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。








浙公网安备 33010602011771号