问题:
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.
解决:
【题意】求一个完全二叉树的节点个数。
① 完全二叉树的一个性质是,如果左子树最左边的深度,等于右子树最右边的深度,说明这个二叉树是满的,即最后一层也是满的,则以该节点为根的树其节点一共有2 ^ h - 1个。如果不等于,则是左子树的节点数,加上右子树的节点数,加上自身这一个。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {//297ms
public static int countNodes(TreeNode root) {
int lheight = 0;
int rheight = 0;
TreeNode pleft = root;
TreeNode pright = root;
while (pleft != null){
lheight ++;
pleft = pleft.left;
}
while (pright != null){
rheight ++;
pright = pright.right;
}
if (lheight == rheight){
return (int)Math.pow(2,lheight) - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
② 直接统计
class Solution {//21ms
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int count = 1;
while(! queue.isEmpty()){
TreeNode temp = queue.poll();
if(temp.val != -1){
temp.val = -1;//用于标识该节点已经遍历过
if(temp.left != null){
queue.offer(temp.left);
count ++;
}
if(temp.right != null){
queue.offer(temp.right);
count ++;
}
}
}
return count;
}
}
class Solution {//11ms
public int countNodes(TreeNode root) {
if (root == null)
return 0;
if (root.val != -1) {
root.val = -1;
return 1 + countNodes(root.left) + countNodes(root.right);
} else {
return 0;
}
}
}