101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
题目链接:https://leetcode-cn.com/problems/symmetric-tree/
思路
自己想题时想了5分钟也没想出来,思维太执着于与用遍历的方法解决这个问题,而没有突破思维定式。
镜面是左右两个子树比较,需要告诉程序是哪两个东西相互比较,那么应该要向程序输入两个比较节点。而题目给的接口只有一个参数,从一个节点(一个子树的根节点)出发,是不知道当前节点和哪个节点对应,因此就不知道如何向下递归,找不到对应的比较位置。
法一:递归
由于给定的函数接口只传入一个参数,因此我们需要自己构造一个两个参数的判定镜像的函数,用来比较传入的两个节点是否一致,一致再进入下一层的对应位置继续比较。
/**
* 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* root) {
if(root==NULL) return true;
return isMirror(root->left, root->right);
}
bool isMirror(TreeNode* l, TreeNode* r){
if(!l && !r) return true;
if(l && r && l->val==r->val) {
return (isMirror(l->left,r->right) && isMirror(l->right,r->left));
}
else return false;
}
};
法二:非递归
用队列来实现上面的递归方法。
一个队列即可,两个队列会加大内存开销。
/**
* 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* root) {
if(root==NULL) return true;
queue<TreeNode*> q;
q.push(root->left);
q.push(root->right);
while(!q.empty()){
auto l = q.front();
q.pop();
auto r = q.front();
q.pop();
if(!l && !r) continue;
else if(l && r && l->val==r->val){
q.push(l->left);
q.push(r->right);
q.push(l->right);
q.push(r->left);
}
else return false;
}
return true;
}
};