题解 | #统计农场牛数量# java
统计农场牛数量
https://www.nowcoder.com/practice/c18924a6debf437180d77baec91dc586
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 res = 0;
public int countNodes (TreeNode root) {
// write code here
if (root == null) {
return 0;
}
dfs(root, 1);
return res;
}
private void dfs(TreeNode root, int cur) {
if (root == null) {
return;
}
res = Math.max(res, cur);
dfs(root.left, cur << 1);
dfs(root.right, (cur << 1) | 1);
}
}
这段代码使用的是Java语言。
这道题目考察的是二叉树的遍历和递归算法。具体来说,代码实现了计算二叉树中节点个数的功能。
代码中的 countNodes 方法接收一个 TreeNode 类型的参数 root,表示二叉树的根节点。接下来,代码调用了 dfs 方法进行深度优先搜索。
在 dfs 方法中,首先判断当前节点 root 是否为空,如果为空,则直接返回。否则,将 cur 与表示当前层数的最大值 res 进行比较,将较大的值保存到 res 中。然后,代码递归调用 dfs 方法遍历左子树和右子树。对于遍历右子树的操作,通过将 cur 左移1位并加上二进制表示中的1((cur << 1) | 1),可以保持每一层的节点值唯一,用于计算节点的最大个数。
三奇智元机器人科技有限公司公司福利 65人发布


查看9道真题和解析