LeetCode 100.Same Tree

LeetCode 100.Same Tree

Description:

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input: 1 1
/ \ / \
2 3 2 3

[1,2,3],   [1,2,3]

Output: true

Example 2:

Input: 1 1
/ \
2 2

[1,2],     [1,null,2]

Output: false

Example 3:

Input: 1 1
/ \ / \
2 1 1 2

[1,2,1],   [1,1,2]

Output: false


分析:

一道简单的题目,如果两棵树都为NULL,则返回true;否则从两棵树根部开始判断,若相等,则继续判断左子树,再判断右子树,利用递归即可解决。
这道题我是在做测试样例的时候懵了,因为好久没用过c语言指向结构体的指针,一直写不好main函数,所以又重新复习了一下指向结构体的指针,代码不常写真是不行。

代码如下:

1
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
using namespace std;
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
// return (p != NULL && q != NULL && p->val == q->val
// && isSameTree(p->left, q->left) && isSameTree(p->right, q->right))
// || (p == NULL && q == NULL);

if (p == NULL && q == NULL) return true;
else if (p != NULL && q != NULL && p-> val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right))
return true;
else return false;
}
};
int main() {
Solution s;

int val1;
cin >> val1;
TreeNode tree1(val1);

int left1;
cin >> left1;
TreeNode l1(left1);

int right1;
cin >> right1;
TreeNode r1(right1);
// 构造指向结构体的指针
TreeNode* p;
p = &tree1;
p->left = &l1;
p->right = &r1;

int val2;
cin >> val2;
TreeNode tree2(val2);


int left2;
cin >> left2;
TreeNode l2(left2);

int right2;
cin >> right2;
TreeNode r2(right2);
// 构造指向结构体的指针
TreeNode* q;
q = &tree2;
q->left = &l2;
q->right = &r2;
cout << s.isSameTree(p, q) << endl;
return 0;
}
------本文结束感谢阅读------