[LeetCode] 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
解题思路
这道题目与前一到一样比较简单,应用在树中常用的递归操作就能完成。先比较两个树同一节点的情况,看他们是否同时为空,或者同时不为空且节点的值相等,若满足这两种情况则继续查看一个树的左子节点和另一个的右子节点,右子节点与另一个的左子节点是否对称,最后得到结果。
实验代码
/**
* 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* root) {
if (root == NULL) return true;
return isSymmetric(root->left, root->right);
}
bool isSymmetric(TreeNode* p, TreeNode* q) {
if (p == NULL && q == NULL)
return true;
if ((p == NULL && q != NULL) || (p != NULL && q == NULL) || (p->val != q->val))
return false;
return isSymmetric(p->left, q->right) && isSymmetric(p->right, q->left);
}
};