Sum The Tree(C语言CodeWars)

27 篇文章 2 订阅
本文介绍了一种使用递归方法求解二叉树所有节点值之和的算法,并通过CodeWars测试程序验证了算法的正确性。文章首先定义了二叉树节点的数据结构,然后实现了前序遍历的递归函数来计算节点值总和,最后通过随机生成的二叉树进行测试,确保算法能够准确计算出树的所有节点值之和。
摘要由CSDN通过智能技术生成

解题思路:

(1)递归求解,采用哪种遍历方式都可以

typedef struct node {
  int value;
  struct node* left;
  struct node* right;
}Node;


void preorder(Node* root,int *sum) {
  if(root) {
    *sum = *sum + root->value;
    preorder(root->left,sum);
    preorder(root->right,sum);
  }
  return;
}

int sumTheTreeValues(Node* root) {
  int sum = 0;
  preorder(root,&sum);
  return sum;
}

(2)测试程序CodeWars

#include <criterion/criterion.h>
#include <stdlib.h> // rand(), malloc(), free()
#include <stddef.h> // NULL

struct node
{
  int value;
  struct node* left;
  struct node* right;
};


void build_tree(struct node* current, int sum)
{
  if (sum > 0) current->value = rand()%sum + 1;
  else current->value = 0;
  sum -= current->value;
  
  if (sum > 0) {
    int part = rand()%16 + 1;
    current->left = (struct node*)malloc(sizeof(struct node));
    current->right = (struct node*)malloc(sizeof(struct node));
    
    build_tree(current->left, sum/part);
    build_tree(current->right, sum - sum/part);
  }
  else {
    current->left = current->right = NULL;
  }
}


void remove_tree(struct node* current)
{
  if (current == NULL) return;
  
  remove_tree(current->left);
  remove_tree(current->right);
  free(current);
}


int sumTheTreeValues(struct node*);


void dotest(int expected)
{
  struct node* root = (struct node*)malloc(sizeof(struct node));
  int actual = 0;
  
  build_tree(root, expected);
  
  actual = sumTheTreeValues(root);
  
  if (root != NULL) remove_tree(root);
  root = NULL;
  
  cr_assert_eq(expected, actual, "Expected %d, but got %d.\n", expected, actual);
}


Test(the_multiply_function, should_pass_all_the_tests_provided)
{
  dotest(4);
  dotest(8);
  dotest(15);
  dotest(16);
  dotest(23);
  dotest(42);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值