mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
67 lines
2.6 KiB
Markdown
67 lines
2.6 KiB
Markdown
# [101. Symmetric Tree](https://leetcode.com/problems/symmetric-tree/description/)
|
||
# 思路
|
||
## 思路一: 递归
|
||
最简单的思路就是递归。若一个非空树是对称树,那么其左右子树是互为镜像的。类似[判断两颗树是否相等的题解](https://github.com/ShusenTang/LeetCode/blob/master/100.%20Same%20Tree.md),
|
||
两棵非空树互为镜像的充要条件是:
|
||
* 根的值相同;
|
||
* 且树一的左子树和树二的右子树互为镜像,树一的右子树和树二的左子树互为镜像。
|
||
## 思路二: 非递归
|
||
采用类似层次遍历的方法。对于左子树从上往下**从左往右**层次遍历,对于右子树从上往下**从右往左**层次遍历,遍历过程中进行比较。注意遍历过程中如果某个节点的孩子为空也应将其孩子入队。
|
||
|
||
层次遍历用的队列,其实用栈也是可以的,代码几乎一样,这样就是分别用**根右左**和**根左右**来遍历左右子树,同理空孩子也需要入栈。
|
||
|
||
两种思路都相当于遍历一遍树,所以两种思路的时空复杂度均为O(n)。
|
||
|
||
# C++
|
||
## 思路一
|
||
``` C++
|
||
class Solution {
|
||
private:
|
||
bool isSymmetricSameTree(TreeNode* p, TreeNode* q) { // 判断两棵树是否互为镜像
|
||
if(!p && !q) return true;
|
||
if(!p || !q || p->val != q->val) return false;
|
||
return isSymmetricSameTree(p -> left, q -> right) && \
|
||
isSymmetricSameTree(p -> right, q -> left);
|
||
}
|
||
public:
|
||
bool isSymmetric(TreeNode* root) {
|
||
if(!root) return true;
|
||
return isSymmetricSameTree(root -> left, root -> right);
|
||
}
|
||
};
|
||
```
|
||
## 思路二
|
||
``` C++
|
||
class Solution {
|
||
public:
|
||
bool isSymmetric(TreeNode* root) {
|
||
if(!root) return true;
|
||
|
||
queue<TreeNode *>container1, container2; // use queue
|
||
// stack<TreeNode *>container1, container2; // use stack
|
||
|
||
container1.push(root -> left);
|
||
container2.push(root -> right);
|
||
|
||
TreeNode *p1, *p2;
|
||
while(!container1.empty() && !container2.empty()){
|
||
p1 = container1.front(); p2 = container2.front(); // use queue
|
||
// p1 = container1.top(); p2 = container2.top(); // use stack
|
||
|
||
container1.pop(); container2.pop();
|
||
|
||
if(p1 && p2){
|
||
if(p1 -> val != p2 -> val) return false;
|
||
container1.push(p1 -> left);
|
||
container1.push(p1 -> right);
|
||
container2.push(p2 -> right);
|
||
container2.push(p2 -> left);
|
||
}
|
||
else if(!p1 && !p2) continue;
|
||
else return false;
|
||
}
|
||
return true;
|
||
}
|
||
};
|
||
```
|