对称二叉树

来源:互联网 发布:autodesk的造型软件 编辑:程序博客网 时间:2024/06/01 20:46

题目描述:

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

注意:

这里根节点为null认为也是对称的,对称需要树的结构相同,并且节点对应的值相同


代码:

/*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;elsereturn isDui(pRoot.left,pRoot.right);    }    boolean isDui(TreeNode p1,TreeNode p2){if(p1==null&&p2==null)return true;else if(p1!=null&&p2!=null&&p1.val==p2.val)return true&&isDui(p1.left,p2.right)&&isDui(p1.right,p2.left);elsereturn false;}}

原创粉丝点击