版权声明:转载请注明来源 https://blog.csdn.net/tangyuan_sibal/article/details/88625385
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路:看到树,递归思想,一棵树是否是对称的,可以看这棵树跟它的镜像是否相等,对于前序遍历(根左右),中序遍历(左根右),后序遍历(左右根)要清楚他们的模样。而且这道题不是基于根递归,而是基于左右子节点的递归
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
if(pRoot == null)
return true;
return isSymmetricals(pRoot.left,pRoot.right);
}
private static boolean isSymmetricals(TreeNode rRoot,TreeNode lRoot)
{
if(rRoot==null && lRoot==null)
return true;
if(rRoot!=null && lRoot!=null)
return rRoot.val==lRoot.val
&& isSymmetricals(rRoot.left,lRoot.right)
&& isSymmetricals(rRoot.right,lRoot.left);
return false;
}
}