题解 | #统计农场牛数量#
统计农场牛数量
https://www.nowcoder.com/practice/c18924a6debf437180d77baec91dc586
知识点
树,遍历树
解题思路
遍历整个树,如果当前节点不为空,ans就加一。再将左右字数进行判断操作,最终ans就是树的节点数目。
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 ans = 0;
public int countNodes (TreeNode root) {
// write code here
fun(root);
return ans;
}
public void fun(TreeNode root){
if(root == null) return;
ans += 1;
fun(root.left);
fun(root.right);
}
}
查看30道真题和解析
海康威视公司福利 1158人发布