[题目描述]
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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}"
.
[解题思路]
其实题目描述里已经给出了一种方法,就是先把二叉树序列化,然后就可以比较序列化结果的两位是否一样就可以了,虽然我第一次提交是按照这个方法做的,但是最后我还是为了清晰起见,用了更加明确的方法,用两个栈,左栈保存根节点的左孩子,右栈保存根节点的右孩子,每次从两个栈中取出一个值,然后比较,如果不同则返回false,如果相同则把从左栈中取出的节点的左孩子和右孩子放进左栈;相对的,把右栈中取出的节点的右孩子和左孩子放进右栈。要注意的是左栈取出的节点放孩子的顺序是先左后右,右栈则是先右后左。
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
stack<TreeNode *> lhs;
stack<TreeNode *> rhs;
if (!root)
return true;
if (!root->left && !root->right)
return true;
else if (root->left && root->right) {
lhs.push(root->left);
rhs.push(root->right);
}
else
return false;
TreeNode *lhs_node;
TreeNode *rhs_node;
while (!lhs.empty()) {
lhs_node = lhs.top();
rhs_node = rhs.top();
lhs.pop();
rhs.pop();
if (lhs_node->val != rhs_node->val)
return false;
if (lhs_node->left && !rhs_node->right)
return false;
if (!lhs_node->left && rhs_node->right)
return false;
if (lhs_node->right && !rhs_node->left)
return false;
if (!lhs_node->right && rhs_node->left)
return false;
if (lhs_node->left)
lhs.push(lhs_node->left);
if (lhs_node->right)
lhs.push(lhs_node->right);
if (rhs_node->right)
rhs.push(rhs_node->right);
if (rhs_node->left)
rhs.push(rhs_node->left);
}
return true;
}
};
[源代码]
https://github.com/rangercyh/leetcode/blob/master/Symmetric%20Tree
转载于:https://blog.51cto.com/rangercyh/1306485