题目:
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.
/**
* 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(root == NULL)
return true;
else
return isMirror(root->left, root->right);
}
private:
bool isMirror(TreeNode *p1, TreeNode *p2) {
if(p1 == NULL && p2 == NULL)
return true;
else if(p1 == NULL || p2 == NULL)
return false;
else if(p1->val != p2->val)
return false;
else
return (isMirror(p1->left, p2->right) && isMirror(p1->right, p2->left));
}
};2. 迭代代码
/**
* 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(root == NULL)
return true;
queue<TreeNode*> left_que, right_que;
left_que.push(root->left);
right_que.push(root->right);
while(!left_que.empty() && !right_que.empty()) {
TreeNode *cur_left = left_que.front();
TreeNode *cur_right = right_que.front();
left_que.pop();
right_que.pop();
if(cur_left == NULL && cur_right == NULL)
continue;
else if(cur_left == NULL || cur_right == NULL)
return false;
else if(cur_left->val != cur_right->val)
return false;
left_que.push(cur_left->left);
left_que.push(cur_left->right);
right_que.push(cur_right->right);
right_que.push(cur_right->left);
}
}
};
286

被折叠的 条评论
为什么被折叠?



