mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 101. Symmetric Tree.md
This commit is contained in:
parent
27f86de133
commit
82969c6409
58
101. Symmetric Tree.md
Normal file
58
101. Symmetric Tree.md
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
# [101. Symmetric Tree](https://leetcode.com/problems/symmetric-tree/description/)
|
||||||
|
# 思路
|
||||||
|
## 思路一: 递归
|
||||||
|
最简单的思路就是递归。若一个非空树是对称树,那么其左右子树是互为镜像的。类似[判断两颗树是否相等的题解](https://github.com/ShusenTang/LeetCode/blob/master/100.%20Same%20Tree.md),
|
||||||
|
两棵非空树互为镜像的充要条件是:
|
||||||
|
* 根的值相同;
|
||||||
|
* 且树一的左子树和树二的右子树互为镜像,树一的右子树和树二的左子树互为镜像。
|
||||||
|
## 思路二: 非递归
|
||||||
|
采用类似层次遍历的方法。对于左子树从上往下**从左往右**层次遍历,对于右子树从上往下**从右往左**层次遍历,遍历过程中进行比较。
|
||||||
|
|
||||||
|
# C++
|
||||||
|
## 思路一
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
private:
|
||||||
|
bool isSymmetricSameTree(TreeNode* p, TreeNode* q) { // 判断两棵树是否互为镜像
|
||||||
|
if(p == NULL && q==NULL) return true;
|
||||||
|
if(p == NULL || q == NULL || p -> val != q -> val) return false;
|
||||||
|
return isSymmetricSameTree(p -> left, q -> right) && isSymmetricSameTree(p -> right, q -> left);
|
||||||
|
}
|
||||||
|
public:
|
||||||
|
bool isSymmetric(TreeNode* root) {
|
||||||
|
if(root == NULL) return true;
|
||||||
|
return isSymmetricSameTree(root -> left, root -> right);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
## 思路二
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
bool isSymmetric(TreeNode *root) {
|
||||||
|
if (root == NULL) return true;
|
||||||
|
TreeNode *left, *right;
|
||||||
|
|
||||||
|
queue<TreeNode*> q1, q2;
|
||||||
|
q1.push(root->left);
|
||||||
|
q2.push(root->right);
|
||||||
|
while (!q1.empty() && !q2.empty()){
|
||||||
|
left = q1.front();
|
||||||
|
q1.pop();
|
||||||
|
right = q2.front();
|
||||||
|
q2.pop();
|
||||||
|
if (NULL == left && NULL == right)
|
||||||
|
continue;
|
||||||
|
if (NULL == left || NULL == right)
|
||||||
|
return false;
|
||||||
|
if (left->val != right->val)
|
||||||
|
return false;
|
||||||
|
q1.push(left->left);
|
||||||
|
q1.push(left->right);
|
||||||
|
q2.push(right->right);
|
||||||
|
q2.push(right->left);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user