题解 | #统计农场牛数量#
统计农场牛数量
https://www.nowcoder.com/practice/c18924a6debf437180d77baec91dc586
考察二叉树的深度优先搜索。
本质在于考察二叉树中节点的个数,所以直接深度优先搜索即可,这里选择先序遍历来解决,只要不知null就让计数+1,递归搜索每一个节点以及其子节点即可。
Java代码如下:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
int sum = 0;
public int countNodes (TreeNode root) {
// write code here
if(root==null){
return 0;
}
return sum+1+countNodes(root.left) + countNodes(root.right);
}
}

