試題請參見: 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?
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}"
.解題思路
一般的考慮是遞歸, 遞歸判斷左孩子的左子樹與右孩子的右子樹以及左孩子的右子樹與右孩子的左子樹是否相等.遇到的問題
源代碼
/**
* 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;
}
}
};