1.题目要求,如图所示:
我们可以用两个数组去解决此题:
1.首先我们要用malloc函数去构造两个数组,还要去构造两个数组的长度,代码块如下图所示:
int* p_length = (int*)malloc(sizeof(int));*p_length = 0;int* q_length = (int*)malloc(sizeof(int));*q_length = 0;int* number_p = (int*)malloc(sizeof(int) * 1000);int* number_q = (int*)malloc(sizeof(int) * 1000);
2.我们再使用前序遍历(什么遍历都行)把树中的元素存入数组,代码块如下图所示:
void preorder_traver(struct TreeNode* root,int* number,int* length){if(root == NULL){number[(*length)++] = 10001;//因为存入数组的元素的相同,但路径可能不同,所以我们要存入一个超过范围数来判断它的路径return;}number[(*length)++] = root->val;preorder_traver(root->left,number,length);preorder_traver(root->right,number,length);}
3.再进行判断:
int i = 0;if((*p_length) != (*q_length))return false;for(i = 0;i < (*p_length);i++){if(number_p[i] != number_q[i]){return false;}}return true;
全部代码如下图所示:
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/void preorder_traver(struct TreeNode* root,int* number,int* length){if(root == NULL){number[(*length)++] = 10001;return;}number[(*length)++] = root->val;preorder_traver(root->left,number,length);preorder_traver(root->right,number,length);}
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {int* p_length = (int*)malloc(sizeof(int));*p_length = 0;int* q_length = (int*)malloc(sizeof(int));*q_length = 0;int* number_p = (int*)malloc(sizeof(int) * 1000);int* number_q = (int*)malloc(sizeof(int) * 1000);preorder_traver(p,number_p,p_length);preorder_traver(q,number_q,q_length);int i = 0;if((*p_length) != (*q_length))return false;for(i = 0;i < (*p_length);i++){if(number_p[i] != number_q[i]){return false;}}return true;
}
大家如果觉得可以的话,可以给个免费的赞吗?谢谢大家了^ _ ^