Skip to content

更新了[lcof-28.对称的二叉树]的cpp解法 #349

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions lcof/面试题28. 对称的二叉树/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,46 @@ func isSymme(left *TreeNode, right *TreeNode) bool {
}
```

### **C++**

```cpp
/**
* 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 isSymmetric(TreeNode* a, TreeNode* b) {
// 均为空,则直接返回true。有且仅有一个不为空,则返回false
if (a == nullptr && b == nullptr) {
return true;
} else if (a == nullptr && b != nullptr) {
return false;
} else if (a != nullptr && b == nullptr) {
return false;
}

// 判定值是否相等,和下面的节点是否对称
return (a->val == b->val) && isSymmetric(a->left, b->right) && isSymmetric(a->right, b->left);
}

bool isSymmetric(TreeNode* root) {
if (root == nullptr) {
return true;
}

return isSymmetric(root->left, root->right);
}
};

```
### **...**
```
Expand Down
34 changes: 34 additions & 0 deletions lcof/面试题28. 对称的二叉树/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* 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 isSymmetric(TreeNode* a, TreeNode* b) {
// 均为空,则直接返回true。有且仅有一个不为空,则返回false
if (a == nullptr && b == nullptr) {
return true;
} else if (a == nullptr && b != nullptr) {
return false;
} else if (a != nullptr && b == nullptr) {
return false;
}

// 判定值是否相等,和下面的节点是否对称
return (a->val == b->val) && isSymmetric(a->left, b->right) && isSymmetric(a->right, b->left);
}

bool isSymmetric(TreeNode* root) {
if (root == nullptr) {
return true;
}

return isSymmetric(root->left, root->right);
}
};