101. Symmetric Tree
题目描述:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note: Bonus points if you could solve it both recursively and iteratively.
题目翻译
给定一颗二叉树,判断它是不是自我镜像,就是以中心为轴镜面对称 比如,这个二叉树 [1,2,2,3,4,4,3] 就是对称的:
1
/ \
2 2
/ \ / \
3 4 4 3
但是如下这个 [1,2,2,null,3,null,3] 就不是:
1
/ \
2 2
\ \
3 3
注意:如果你可以递归地和迭代地解决它,你就会得到额外的奖励
解题方案
标签: 树
思路:
解题关键是确定镜面节点对,然后判断该对节点值是否一样即可。通过观察可以发现,只要左子树与右子树镜面对称即可,左子树的左孩子与右子树的右孩子配对,左子树的右孩子与右子树的左孩子配对,因而可以递归求解 也可以迭代求解。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode *lhs, TreeNode *rhs)
{
if (NULL == lhs&&NULL == rhs)return true;
if (NULL!=lhs&&NULL!=rhs&&lhs->val == rhs->val)
{
return isSymmetric(lhs->right, rhs->left) && isSymmetric(lhs->left, rhs->right);
}
return false;
}
bool isSymmetric(TreeNode* root) {
if (!root)return true;
return isSymmetric(root->left, root->right);
}
};