期末考试前,找到了去年的考题:
求二叉树中度为2的结点个数 题目编号:1015
#include <iostream>
using namespace std;
struct TreeNode {
char _val;
TreeNode* _left;
TreeNode* _right;
TreeNode(int val):_val(val), _left(NULL), _right(NULL) {
}
};
class BinTree {
public:
BinTree();
~BinTree();
public:
int getSum();
private:
TreeNode* creat(TreeNode* root);
void release(TreeNode* root);
void preOrder(TreeNode* root);
private:
TreeNode* root_;
int sum_;
};
BinTree::BinTree() {
sum_ = 0;
root_ = creat(root_);
}
BinTree::~BinTree() {
release(root_);
}
TreeNode* BinTree::creat(TreeNode* root) {
char val;
cin >> val;
if (val == '#') root = NULL;
else {
root = new TreeNode(val);
root->_left = creat(root->_left);
root->_right = creat(root->_right);
}
return root;
}
void BinTree::release(TreeNode* root) {
if (root == NULL) return ;
release(root->_left);
release(root->_right);
delete root;
}
void BinTree::preOrder(TreeNode* root) {
if (root == NULL) return ;
if (root->_left != NULL && root->_right != NULL) sum_++;
preOrder(root->_left);
preOrder(root->_right);
}
int BinTree::getSum() {
preOrder(root_);
return sum_;
}
int main() {
BinTree tree;
cout << tree.getSum();
return 0;
}
查找符合某范围的奇数,并按原来顺序输出 题目编号:1016
#include <iostream>
using namespace std;
int main() {
int arr[1024];
int length, left, right;
cin >> length;
for (int i = 0; i < length; i++) {
cin >> arr[i];
}
cin >> left >> right;
for (int i = 0; i < length; i++) {
if (arr[i] >= left && arr[i] <= right && arr[i] & 1 == 1) {
cout << arr[i] << " ";
}
}
return 0;
}
查找符合某范围的3的倍数,并按原来顺序输出 题目编号:1017
#include <iostream>
using namespace std;
int main(