互联网面试宝典

您现在的位置是: 首页 > 数据结构

问题详情

编写一个函数,统计给定二叉树的节点数量。

面试宝典 2023-06-12 Web前端开发工程师 41
```
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
if (leftHeight == rightHeight) {
// 左子树是满二叉树
return (1 << leftHeight) + countNodes(root->right);
} else {
// 右子树是满二叉树
return (1 << rightHeight) + countNodes(root->left);
}
}
private:
// 计算节点高度
int getHeight(TreeNode* node) {
int height = 0;
while (node) {
height++;
node = node->left;
}
return height;
}
};
```

算法思路:

1. 首先计算左子树高度和右子树高度。

2. 如果左子树高度等于右子树高度,说明左子树是满二叉树,而右子树可能不满,所以可以重复上述操作在右子树上进行。相反,如果右子树高度小于左子树,说明右子树是满的,重复上述操作在左子树上进行。

3. 如果当前节点为空,则返回 0,否则节点数应该是 1 + 左子树节点数 + 右子树节点数。

计算节点高度:

采用迭代方法计算二叉树高度,因为完全二叉树的特殊性,只需要不断地访问左节点就可以计算高度。