题目链接:https://leetcode.com/problems/symmetric-tree/
Runtimes:8ms
1、问题
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
2、分析
从左到右, 从右到左,两个操作同时进行,对比看看是否相等,不等则返回false。
3、小结
以为会花多时间,没想到跑得还挺快的。
4、实现
/**
* Definition for binary tree
* 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(NULL == root)
return true;
vector<TreeNode *> v1, v2;
v1.push_back(root);
v2.push_back(root);
while(v1.size() > 0 && v2.size() > 0)
{
TreeNode *t1 = v1.back(); v1.pop_back();
TreeNode *t2 = v2.back(); v2.pop_back();
if(t1->val != t2->val)
return false;
if(NULL != t1->left && NULL != t2->right)
{
v1.push_back(t1->left);
v2.push_back(t2->right);
}else if(NULL == t1->left && NULL == t2->right)
{
}else{
return false;
}
if(NULL != t1->right && NULL != t2->left)
{
v2.push_back(t1->right);
v1.push_back(t2->left);
}else if(NULL == t1->right && NULL == t2->left){
}else{
return false;
}
}
return true;
}
};
5、反思
树的非递归操作,熟练一些,一气呵成。