此篇文章為我的解題紀錄,程式碼或許並不是很完善

Leetcode - 101. Symmetric Tree

解題思路

用recursive來將每個節點傳入並判斷他是否有左右節點且和他對應位置的節點內存的值是否相等

我滴程式碼

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL)
{
return true;
}
else
{
return sym(root->left, root->right);
}
}

bool sym(TreeNode* left, TreeNode* right)
{
if (left == NULL && right == NULL)
{
return true;
}
else if (left == NULL || right == NULL)
{
return false;
}
else if (left->val != right->val)
{
return false;
}
else
{
return sym(left->left, right->right) && sym(right->left, left->right);
}
}
};