求二叉树节点个数
递归解法
/**
* 获取二叉树节点数量
* @param node
* @return
*/
public int getNodeCount(TreeNode node){
if (node == null){//二叉树为空,节点个数为0
return 0;
}
return getNodeCount(node.left) + getNodeCount(node.right) + 1;//二叉树不为空,二叉树节点个数 = 左子树节点个数 + 右子树节点个数 + 1
}
非递归解法
这里使用了层序遍历的方式。
/**
* 获取二叉树节点数量
* @param node
* @return
*/
public int getNodeCount2(TreeNode node){
if (node == null){//二叉树为空,节点个数为0
return 0;
}
int count = 0;
LinkedList<TreeNode> linkedList = new LinkedList<>();
linkedList.add(node);
while (!linkedList.isEmpty()){
TreeNode tmp = linkedList.poll();
count++;
if (tmp.left != null){
linkedList.add(tmp.left);
}
if (tmp.right != null){
linkedList.add(tmp.right);
}
}
return count;
}