思路描述
DFS
1.我们将统计二叉树中节点个数的问题进行分解(问题分解这种思路也是求解涉及二叉树递归中的一种大思路!!!):
1.1 将统计二叉树中节点的个数的问题分解为:统计其左子树节点个数+统计其右子树节点个数
1.2为了统计左右子树节点的个数那么我们必须首先要知道其左右子树节点的个数,即由此我们想到先需要利用二叉树后序遍历的大框架来解决问题.(可能在看下面代码实现时候会稍微疑惑一下下为什么是int count = leftCount + rightCount + 1;为什么要加一,原因很简单,因为我们在往上归的过程中还需要将当前子树的根节点也计算到里面去,所以需要加一)
BFS
BFS理解较简单直接套用BFS模板,再维护一个int 类型的变量count用于记录二叉树中节点的个数即可
代码
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
/**
* Count the node of binary tree(BFS)
*
* @param root The root node of binary tree
* @return int
*/
private int countByBFS(TreeNode root) {
int count = 0;
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
count++;
while (!queue.isEmpty()) {
int curLeveSize = queue.size();
for (int i = 0; i < curLeveSize; ++i) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
count++;
}
if (node.right != null) {
queue.add(node.right);
count++;
}
}
}
return count;
}
/**
* Count the node of binary tree(DFS)
*
* @param root The root node of binary tree
* @return int
*/
private int countByDFS(TreeNode root) {
if (root == null) {
return 0;
}
int leftCount = countByDFS(root.left);
int rightCount = countByDFS(root.right);
int count = leftCount + rightCount + 1;
return count;
}
}