mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
update 101
This commit is contained in:
parent
484624b427
commit
baa885ae3a
@ -6,7 +6,9 @@
|
|||||||
* 根的值相同;
|
* 根的值相同;
|
||||||
* 且树一的左子树和树二的右子树互为镜像,树一的右子树和树二的左子树互为镜像。
|
* 且树一的左子树和树二的右子树互为镜像,树一的右子树和树二的左子树互为镜像。
|
||||||
## 思路二: 非递归
|
## 思路二: 非递归
|
||||||
采用类似层次遍历的方法。对于左子树从上往下**从左往右**层次遍历,对于右子树从上往下**从右往左**层次遍历,遍历过程中进行比较。
|
采用类似层次遍历的方法。对于左子树从上往下**从左往右**层次遍历,对于右子树从上往下**从右往左**层次遍历,遍历过程中进行比较。注意遍历过程中如果某个节点的孩子为空也应将其孩子入队。
|
||||||
|
|
||||||
|
两种思路都相当于遍历一遍树,所以两种思路的时空复杂度均为O(n)。
|
||||||
|
|
||||||
# C++
|
# C++
|
||||||
## 思路一
|
## 思路一
|
||||||
@ -14,13 +16,14 @@
|
|||||||
class Solution {
|
class Solution {
|
||||||
private:
|
private:
|
||||||
bool isSymmetricSameTree(TreeNode* p, TreeNode* q) { // 判断两棵树是否互为镜像
|
bool isSymmetricSameTree(TreeNode* p, TreeNode* q) { // 判断两棵树是否互为镜像
|
||||||
if(p == NULL && q==NULL) return true;
|
if(!p && !q) return true;
|
||||||
if(p == NULL || q == NULL || p -> val != q -> val) return false;
|
if(!p || !q || p->val != q->val) return false;
|
||||||
return isSymmetricSameTree(p -> left, q -> right) && isSymmetricSameTree(p -> right, q -> left);
|
return isSymmetricSameTree(p -> left, q -> right) && \
|
||||||
|
isSymmetricSameTree(p -> right, q -> left);
|
||||||
}
|
}
|
||||||
public:
|
public:
|
||||||
bool isSymmetric(TreeNode* root) {
|
bool isSymmetric(TreeNode* root) {
|
||||||
if(root == NULL) return true;
|
if(!root) return true;
|
||||||
return isSymmetricSameTree(root -> left, root -> right);
|
return isSymmetricSameTree(root -> left, root -> right);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -30,24 +33,19 @@ public:
|
|||||||
class Solution {
|
class Solution {
|
||||||
public:
|
public:
|
||||||
bool isSymmetric(TreeNode *root) {
|
bool isSymmetric(TreeNode *root) {
|
||||||
if (root == NULL) return true;
|
if (!root) return true;
|
||||||
TreeNode *left, *right;
|
|
||||||
|
|
||||||
|
TreeNode *left, *right;
|
||||||
queue<TreeNode*> q1, q2;
|
queue<TreeNode*> q1, q2;
|
||||||
q1.push(root->left);
|
q1.push(root->left);
|
||||||
q2.push(root->right);
|
q2.push(root->right);
|
||||||
|
|
||||||
while (!q1.empty() && !q2.empty()){
|
while (!q1.empty() && !q2.empty()){
|
||||||
left = q1.front();
|
left = q1.front(); q1.pop();
|
||||||
q1.pop();
|
right = q2.front(); q2.pop();
|
||||||
right = q2.front();
|
if (!left && !right) continue;
|
||||||
q2.pop();
|
if (!left || !right || left->val != right->val) return false;
|
||||||
if (NULL == left && NULL == right)
|
q1.push(left->left);
|
||||||
continue;
|
|
||||||
if (NULL == left || NULL == right)
|
|
||||||
return false;
|
|
||||||
if (left->val != right->val)
|
|
||||||
return false;
|
|
||||||
q1.push(left->left);
|
|
||||||
q1.push(left->right);
|
q1.push(left->right);
|
||||||
q2.push(right->right);
|
q2.push(right->right);
|
||||||
q2.push(right->left);
|
q2.push(right->left);
|
||||||
|
Loading…
Reference in New Issue
Block a user