Skip to content

Commit fbdab49

Browse files
authored
Merge pull request gzc426#285 from gityjx/master
upload
2 parents ff1b8f6 + 793c857 commit fbdab49

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

2018.12.4-leetcode101/halfofwater.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
## Leetcode 101
2+
3+
4+
### 递归解法:
5+
6+
``` C++
7+
/**
8+
* Definition for a binary tree node.
9+
* struct TreeNode {
10+
* int val;
11+
* TreeNode *left;
12+
* TreeNode *right;
13+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
14+
* };
15+
*/
16+
class Solution {
17+
public:
18+
bool isSymmetric(TreeNode* root) {
19+
return helper(root, root);
20+
}
21+
bool helper(TreeNode *left, TreeNode *right) {
22+
if (left == NULL && right == NULL) return true;
23+
if (left == NULL || right == NULL) return false;
24+
25+
if (left->val != right->val) return false;
26+
return helper(left->left, right->right) && helper(left->right, right->left);
27+
28+
}
29+
};
30+
31+
```
32+
33+
### 迭代解法:
34+
``` C++
35+
/**
36+
* Definition for a binary tree node.
37+
* struct TreeNode {
38+
* int val;
39+
* TreeNode *left;
40+
* TreeNode *right;
41+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
42+
* };
43+
*/
44+
class Solution {
45+
public:
46+
bool isSymmetric(TreeNode* root) {
47+
std::queue<TreeNode *> q;
48+
q.push(root);
49+
q.push(root);
50+
while (!q.empty()) {
51+
TreeNode* t1 = q.front();
52+
q.pop();
53+
TreeNode* t2 = q.front();
54+
q.pop();
55+
if (t1 == NULL && t2 == NULL) continue;
56+
if (t1 == NULL || t2 == NULL) return false;
57+
if (t1->val != t2->val) return false;
58+
q.push(t1->left);
59+
q.push(t2->right);
60+
q.push(t1->right);
61+
q.push(t2->left);
62+
}
63+
return true;
64+
}
65+
};
66+
67+
```

0 commit comments

Comments
 (0)