求基于二叉链存储的二叉树中(随机生成节点数值,至少包括50个节点)所有祖父节点为偶数的节点的和,如果不存在这样的节点则返回0。
可采用多种方式,遍历也可用多种方式,下面采用了两种方法
第一种方法
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
//二叉树节点结构体
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode *parent;
TreeNode(int x) : val(x),left(NULL),right(NULL){}
};
//输出二叉树
void DispTree(TreeNode *b)
{
if(b!=NULL)
{
cout<<b->val;
if(b->left!=NULL || b->right!=NULL)
{
cout<<"(";
DispTree(b->left);
if(b->right!=NULL)
cout<<",";
DispTree(b->right);
cout<<")";
}
}
}
//判断一个节点是否为偶数祖父节点
bool Judgement(TreeNode *root)
{
if(!root || !root->parent || !root->parent->parent)
{
return false;
}
return(root->parent->parent->val %2==0);
}
//遍历二叉树找偶数祖父节点并求和
int sumGrandparent(TreeNode *root)
{
if(!root)
{
return 0;
}
int sum=0;
if(Judgement(root))
{
sum+=root->val;
}
sum+=sumGrandparent(root->left);
sum+=sumGrandparent(root->right);
return sum;
}
//主函数
int main()
{
srand(time(0));
//随机生成二叉树
TreeNode *root=new TreeNode(rand()%100);
for(int i=0;i<49;i++)
{
int val=rand()%100;
TreeNode *node=new TreeNode(val);
TreeNode *cur=root;
while(true)
{
if(rand()%2==0)
{
if(!cur->left)
{
cur->left=node;
node->parent=cur;
break;
}
else{cur=cur->left;}
}
else
{
if(!cur->right)
{
cur->right=node;
node->parent=cur;
break;
}
else {cur=cur->right;}
}
}
}
//输出二叉树
cout<<"输出二叉树:";
DispTree(root);
cout<<endl;
//计算祖父节点的和
int sum=sumGrandparent(root);
cout<<"所有祖父节点为偶数节点的和为:"<<sum<<endl;
return 0;
}
另一种方法
#include<iostream>
#include<cstabilsh>
#include<ctime>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode* parent;
TreeNode(int x) : val(x), left(NULL), right(NULL), parent(NULL) {}
};
TreeNode* generateTree(int n) {
if (n <= 0) return NULL;
int val = rand() % 100;
TreeNode* root = new TreeNode(val);
root->left = generateTree(n / 2);
root->right = generateTree(n - n / 2 - 1);
if (root->left) root->left->parent = root;
if (root->right) root->right->parent = root;
return root;
}
int sumEvenGrandparent(TreeNode* root) {
if (!root) return 0;
int sum = 0;
if (root->parent && root->parent->parent && root->parent->parent->val % 2 == 0) {
sum += root->val;
}
sum += sumEvenGrandparent(root->left);
sum += sumEvenGrandparent(root->right);
return sum;
}
int main() {
srand(time(NULL));
TreeNode* root = generateTree(50);
int sum = sumEvenGrandparent(root);
cout << "The sum of nodes whose grandparent is even is " << sum << endl;
return 0;
}