题目:leetcode222. 完全二叉树的节点个数(递归法三行代码!层次遍历更节省空间!)
描述:
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
思路
这里提供两种思路,一种是递归的解决方案,将当前节点的数量加入count,然后计算左子树和右子树的结点数量,然后加到count即可,当递归到叶子结点的时候,返回0;
第二种是层次遍历的方法,一个个遍历然后递增count即可,详细看下列代码。
代码
递归法
public class Solution {
public int countNodes(TreeNode root)
{
if(root==null)
return 0;
return 1+countNodes(root.left)+countNodes(root.right);
}
}
层次遍历法(广度优先算法)
import java.util.Deque;
import java.util.LinkedList;
public class Solution {
public int countNodes(TreeNode root)
{
if(root==null)
return 0;
int count=0;
int length;
Deque<TreeNode> deque=new LinkedList<>();
deque.offer(root);
while(!deque.isEmpty())
{
length=deque.size();
count+=length;
TreeNode node;
while(length>0)
{
node=deque.poll();
if(node.left!=null)
deque.offer(node.left);
if(node.right!=null)
deque.offer(node.right);
length--;
}
}
return count;
}
}