题解 | #统计农场牛数量# 完全二叉树
统计农场牛数量
https://www.nowcoder.com/practice/c18924a6debf437180d77baec91dc586
知识点
完全二叉树
思路
完全二叉树的父节点编号若为x,那么左儿子的编号是x << 1; 右儿子的编号为x << 1 | 1
遍历二叉树,取最大的编号即可,编号从1开始。
时间复杂度
和节点个数成正比,
AC code(C++)
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
int res = 0;
int countNodes(TreeNode* root) {
if (!root) return 0;
dfs(root, 1);
return res;
}
void dfs(TreeNode* root, int cur) {
if (!root) return;
res = max(res, cur);
dfs(root->left, cur << 1);
dfs(root->right, cur << 1 | 1);
}
};
查看19道真题和解析
