50143. AND & OR of Trees
難度:3/5
Second Try: 2/5 Used Time: 9:271
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36#include <stdio.h>
#include <stdlib.h>
#include "tree.h"
Node *treeAND(Node *root1, Node *root2){
if(root1 == NULL || root2 == NULL) return NULL;
Node* new_root = (Node*) malloc(sizeof(Node));
new_root->val = root1->val * root2->val;
new_root->left = treeAND(root1->left, root2->left);
new_root->right = treeAND(root1->right, root2->right);
return new_root;
}
Node *treeOR(Node *root1, Node *root2){
if(root1 == NULL && root2 == NULL) return NULL;
Node* new_root = (Node*) malloc(sizeof(Node));
if(root2 == NULL){
new_root->val = root1->val;
new_root->left = treeOR(root1->left, NULL);
new_root->right = treeOR(root1->right, NULL);
}
else if(root1 == NULL){
new_root->val = root2->val;
new_root->left = treeOR(NULL, root2->left);
new_root->right = treeOR(NULL, root2->right);
}
else{
new_root->val = root1->val + root2->val;
new_root->left = treeOR(root1->left, root2->left);
new_root->right = treeOR(root1->right, root2->right);
}
return new_root;
}