对称树 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:
But the following is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
示例
示例1
输入
{1,2,2}
输出
true
示例2
输入
{1,2,3,3,#,2,#}
输出
false
解题思路
- 明确check函数的功能:判断以root1和root2为根节点的两棵树是否对称
- 两个节点均为空,直接返回true
- 两个节点一个为空,另一个不空,直接返回false
- 两个节点均不为空,且节点值不相等,直接返回false
- 两个节点均不为空,且节点值相等,则继续递归
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
return check(root -> left, root -> right);
}
//判断以root1和root2为根节点的两棵树是否对称
bool check(TreeNode* root1, TreeNode* root2) {
//两个节点均为空,直接返回true
if(!root1 && !root2) return true;
//两个节点一个为空,另一个不空,直接返回false
if(!root1 || !root2) return false;
//两个节点均不为空
if(root1 -> val == root2 -> val) {
//节点值相等,则继续递归
return check(root1 -> left, root2 -> right) && check(root1 -> right, root2 -> left);
} else {
//节点值不相等,直接返回false
return false;
}
}
};