BST 中的偶数求和

sum even numbers in BST

在这段代码中,我需要创建一个函数来对我的 BST 中的偶数求和。我不知道如何传递树的所有节点。这是代码:

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int key;
    struct node *left, *right;
};

struct node *newNode(int item) {
struct node *temp=(struct node *)malloc(sizeof(struct node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}

struct node* insert(struct node* node, int key) {
    if (node == NULL) return newNode(key);
    if (key < node->key)
        node->left = insert(node->left, key);
    else
        node->right = insert(node->right, key);
    return node;
}

void main(void)
{
    struct node *root = NULL;
    int data[]={3,1,2,6,4,7,8}, n, i;
    n=sizeof(data)/sizeof(data[0]);
    for(i=0;i<n;i++)
        root=insert(root,data[i]);
}

您需要执行不同的搜索(BFS 或 DFS)之一,以便在树的每个节点中进行搜索。同样在每时每刻,您都应该保存偶数的实际总和。比较应该是这样的

if(node->key % 2 == 0){
    final += node->key;
}

希望对您有所帮助。

尝试这样的事情。抱歉,手边没有C编译器。

int sum(struct node *root) {
   if (root == NULL) {
     return 0;
   }
   int value = 0;
   if (root->key % 2 == 0) {
      value = root->key;
   }
   return value + sum(root->left) + sum(root->right);
}