题目描述
请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
- 示例1
//输入
{8,6,6,5,7,7,5} // 8,6,6
// 返回值
true
- 示例2
//输入
{8,6,9,5,7,7,5} // 8,6,9
// 返回值
false
题解
思路一:递归
把输入的树看成两棵树,一个遍历左子树,另一个表来遍历右子树,然后逐一比较遍历结果。
- 设置一个递归函数
isSame(r1, r2)
,表示如果对称,返回true,否则返回false - 递归终止条件:
r1==nullptr && r2==nulllptr
, 直接返回true,否则,如果只有一个为nullptr,返回false - 下一步递归:如果r1->val == r2->val, 则isSame(root1->left, root2->right) && isSame(root1->right, root2->left);
- C#:
/*
public class TreeNode
{
public int val; // 树子节点的值
public TreeNode left; //左指针
public TreeNode right; //右指针
public TreeNode (int x)
{
val = x;
}
}*/
递归函数isSame(TreeNode pRoot1, TreeNode pRoot2)
class Solution
{
public bool isSymmetrical(TreeNode pRoot)
{
// write code here
return isSame(pRoot, pRoot);
}
bool isSame(TreeNode pRoot1, TreeNode pRoot2)
{
if (pRoot1 == null && pRoot2 == null) // 输入树为空, 返回true
{
return true;
}
if (pRoot1 == null || pRoot2 == null) // 输入树为空的情况在上一部分已经return
{
return false;
}
if (pRoot1.val != pRoot2.val)
{
return false;
}
return isSame(pRoot1.left, pRoot2.right) && isSame(pRoot1.right, pRoot2.left);
}
}
重载函数 isSymmetrical(TreeNode pRoot1, TreeNode pRoot2)
class Solution
{
public bool isSymmetrical(TreeNode pRoot)
{
// write code here
return isSymmetrical(pRoot, pRoot);
}
bool isSymmetrical(TreeNode pRoot1, TreeNode pRoot2)
{
if (pRoot1 == null && pRoot2 == null)
{
return true;
}
if (pRoot1 == null || pRoot2 == null)
{
return false;
}
if (pRoot1.val != pRoot2.val)
{
return false;
}
return isSymmetrical(pRoot1.left, pRoot2.right) && isSymmetrical(pRoot1.right, pRoot2.left);
}
}