用c 语言写一段二叉树合并的代码以下是使用C语言实现二叉树合并的代码:c#include stdioh#include stdlibhstruct TreeNode int val; struct TreeNode left; struct TreeNode right;;struct TreeNode mergeTreesstruct TreeNode t1 struct
完善代码:#include <stdio.h>#include <stdlib.h>struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right;};struct TreeNode* mergeTrees(struct TreeNode* t1, struct TreeNode* t2) { if (t1 == NULL) { return t2; } if (t2 == NULL) { return t1; } t1->val += t2->val; t1->left = mergeTrees(t1->left, t2->left); t1->right = mergeTrees(t1->right, t2->right); return t1;}int main() { struct TreeNode* t1 = (struct TreeNode*)malloc(sizeof(struct TreeNode)); t1->val = 1; t1->left = (struct TreeNode*)malloc(sizeof(struct TreeNode)); t1->left->val = 3; t1->left->left = (struct TreeNode*)malloc(sizeof(struct TreeNode)); t1->left->left->val = 5; t1->left->left->left = NULL; t1->left->left->right = NULL; t1->left->right = NULL; t1->right = (struct TreeNode*)malloc(sizeof(struct TreeNode)); t1->right->val = 2; t1->right->left = NULL; t1->right->right = NULL; struct TreeNode* t2 = (struct TreeNode*)malloc(sizeof(struct TreeNode)); t2->val = 2; t2->left = (struct TreeNode*)malloc(sizeof(struct TreeNode)); t2->left->val = 1; t2->left->left = NULL; t2->left->right = (struct TreeNode*)malloc(sizeof(struct TreeNode)); t2->left->right->val = 4; t2->left->right->left = NULL; t2->left->right->right = NULL; t2->right = (struct TreeNode*)malloc(sizeof(struct TreeNode)); t2->right->val = 3; t2->right->left = NULL; t2->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode)); t2->right->right->val = 7; t2->right->right->left = NULL; t2->right->right->right = NULL; struct TreeNode* t = mergeTrees(t1, t2); printf("%d\n", t->val); printf("%d\n", t->left->val); printf("%d\n", t->left->left->val); printf("%d\n", t->left->right->val); printf("%d\n", t->right->val); printf("%d\n", t->right->right->val); return 0;}在main函数中,我们创建了两个二叉树t1和t2,并将它们传递给mergeTrees函数来合并它们。然后,我们打印合并后的二叉树的节点值,以验证合并是否正确。
原文地址: https://www.cveoy.top/t/topic/bVew 著作权归作者所有。请勿转载和采集!