Leetcode题解 101. Symmetric Tree

来源:互联网 发布:linux 图形库 编辑:程序博客网 时间:2024/06/01 14:10

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1   / \  2   2 / \ / \3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1   / \  2   2   \   \   3    3

用递归来做,刚开始先1,对二叉树求镜像,2,再比较。
其实第一步是多余的,直接比较即可。
left.left 和 right.right 比
left.right 和 right.left 比 即可得出结果。
left.val==right.val这个条件虽然不添加也能AC,但是添加后可以减少比较次数,优化算法

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isSymmetric(TreeNode root) {        if(null==root)  return true;        return checkEquals(root.left,root.right);    }    static boolean checkEquals(TreeNode left,TreeNode right){        if((left==null&&right==null)) return true;        else if(left==null||right==null)  return false;        else if(left.val!=right.val)  return false;        else  return               left.val==right.val&&checkEquals(left.left,right.right)&&checkEquals(left.right,right.left);    }}
0 0
原创粉丝点击