Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d635a4c

Browse files
ChunelFengjunfeng.fj
and
junfeng.fj
authored
更新了[lcof-28.对称的二叉树]的cpp解法 (doocs#349)
Co-authored-by: junfeng.fj <junfeng.fj@alibaba-inc.com>
1 parent 375a1c7 commit d635a4c

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

‎lcof/面试题28. 对称的二叉树/README.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,46 @@ func isSymme(left *TreeNode, right *TreeNode) bool {
150150
}
151151
```
152152

153+
### **C++**
154+
155+
```cpp
156+
/**
157+
* Definition for a binary tree node.
158+
* struct TreeNode {
159+
* int val;
160+
* TreeNode *left;
161+
* TreeNode *right;
162+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
163+
* };
164+
*/
165+
166+
class Solution {
167+
public:
168+
bool isSymmetric(TreeNode* a, TreeNode* b) {
169+
// 均为空,则直接返回true。有且仅有一个不为空,则返回false
170+
if (a == nullptr && b == nullptr) {
171+
return true;
172+
} else if (a == nullptr && b != nullptr) {
173+
return false;
174+
} else if (a != nullptr && b == nullptr) {
175+
return false;
176+
}
177+
178+
// 判定值是否相等,和下面的节点是否对称
179+
return (a->val == b->val) && isSymmetric(a->left, b->right) && isSymmetric(a->right, b->left);
180+
}
181+
182+
bool isSymmetric(TreeNode* root) {
183+
if (root == nullptr) {
184+
return true;
185+
}
186+
187+
return isSymmetric(root->left, root->right);
188+
}
189+
};
190+
191+
```
192+
153193
### **...**
154194
155195
```
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
11+
class Solution {
12+
public:
13+
bool isSymmetric(TreeNode* a, TreeNode* b) {
14+
// 均为空,则直接返回true。有且仅有一个不为空,则返回false
15+
if (a == nullptr && b == nullptr) {
16+
return true;
17+
} else if (a == nullptr && b != nullptr) {
18+
return false;
19+
} else if (a != nullptr && b == nullptr) {
20+
return false;
21+
}
22+
23+
// 判定值是否相等,和下面的节点是否对称
24+
return (a->val == b->val) && isSymmetric(a->left, b->right) && isSymmetric(a->right, b->left);
25+
}
26+
27+
bool isSymmetric(TreeNode* root) {
28+
if (root == nullptr) {
29+
return true;
30+
}
31+
32+
return isSymmetric(root->left, root->right);
33+
}
34+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /