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? > read more on how binary tree is serialized(序列) on OJ.(OJ是Online Judge系统的简称,用来在线检测程序源代码的正确性)
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? > read more on how binary tree is serialized(序列) on OJ.(OJ是Online Judge系统的简称,用来在线检测程序源代码的正确性)
Hide Tags Tree Depth-first Search(树的深度优先搜索)
解题思路:根节点进行左右子节点判断,子节点对其同级子节点进行子节点的左右判断,使用递归与迭代的思想即可实现。
代码如下:
public class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x)
{
val = x;
}
}
public boolean isSymmetric(TreeNode root)
{
if(root==null)
{
return false;
}
else
{
boolean output=equalNode(root.left,root.right);
return output;
}
}
public boolean equalNode(TreeNode p,TreeNode q)
{
//如果需要判定的两节点均为空,返回true
if(p==null&&q==null)
{
return true;
}
//如果需要判定的两节点有一个为空,另一个非空,返回false
if(p==null&&q!=null)
{
return false;
}
if(p!=null&&q==null)
{
return false;
}
//如果需要判定的两节点值相等,则继续往下判定,此处采用递归与迭代思想
if(p.val==q.val)
{
return equalNode(p.left,q.right)&&equalNode(p.right,q.left);
}
else
{
return false;
}
}