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.
題意:對(duì)稱(鏡像)二叉樹
思路:什么是對(duì)稱(鏡像)二叉樹?
1.兩個(gè)根結(jié)點(diǎn)的值要相等
2.左邊的左子樹和右邊的右子樹對(duì)稱
3.左邊的右子樹和右邊的左子樹對(duì)稱
注意:
1.空結(jié)點(diǎn)對(duì)稱
2.如果左子樹和右子樹只有一個(gè)為空則不對(duì)稱
/**
* 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)
return true;
return dfs(root->left,root->right);
}
bool dfs(TreeNode*p,TreeNode*q)
{
if(!p||!q)
return !p && !q;//如果左子樹和右子樹只有一個(gè)為空則不對(duì)稱
return p->val==q->val&&dfs(p->left,q->right)&&dfs(p->right,q->left);
}
};
迭代:
/**
* 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)
return true;
stack<TreeNode*>left,right;
auto l=root->left,r=root->right;
while(l||r||left.size()||right.size())
{
while(l&&r)
{
left.push(l),
l=l->left;
right.push(r);
r=r->right;
}
if(l||r)
return false;
l=left.top(),left.pop();
r=right.top(),right.pop();
if(l->val!=r->val)
return false;
l=l->right,r=r->left;
}
return true;
}
};