对称的二叉树

来源:互联网 发布:vb程序设计第二版答案 编辑:程序博客网 时间:2024/05/16 19:02

1、链接:对称的二叉树
来源:牛客网
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

2、思路:采用递归
3、代码:

boolean isSymmetrical(TreeNode pRoot) {        boolean res = true;        if (pRoot == null)            return true;        res = isSame(pRoot.left, pRoot.right);        return res;    }    private boolean isSame(TreeNode left_root, TreeNode right_root) {        boolean isOutsideSame = false;        boolean isInsideSame = false;        if ((left_root.left != null && right_root.right == null)||            (left_root.left == null && right_root.right != null)||            (left_root.right != null && right_root.left == null)||            (left_root.right == null && right_root.left != null)||             left_root.val != right_root.val) {            return false;        } else {            if (left_root.left != null && right_root.right != null) {                isOutsideSame = isSame(left_root.left, right_root.right);            } else if (left_root.left == null && right_root.right == null) {                isOutsideSame = true;            }            if (left_root.right != null && right_root.left != null) {                isInsideSame = isSame(left_root.right, right_root.left);            } else if (left_root.right == null && right_root.left == null) {                isInsideSame = true;            }        }        return isOutsideSame && isInsideSame;    }
原创粉丝点击