试题请参见: https://oj.leetcode.com/problems/symmetric-tree/
题目概述
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?
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 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.
解题思路
一般的考虑是递归, 递归判断左孩子的左子树与右孩子的右子树以及左孩子的右子树与右孩子的左子树是否相等.遇到的问题
一共192个测试测试点, 简直丧心病狂.
除了判断结构是否对称以外, 还需要判断数值是否相同.
一开始没有判断, 于是就WA了.
源代码
/**
* 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 isSymmetric(root->left, root->right);
}
}
private:
bool isSymmetric(TreeNode *left, TreeNode *right) {
if ( left == NULL && right == NULL ) {
return true;
} else if ( left != NULL && right != NULL ) {
if ( left->val != right->val ) {
return false;
}
if ( isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left) ) {
return true;
} else {
return false;
}
} else {
return false;
}
}
};