题目:
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
题意:
给定一棵二叉树,判定它是否是自己的一个镜像(即 关于它的中心对称)
比如下面这课二叉树就是对称的:
1 / 2 2 / \ / 3 4 4 3
但是下面的这个不是:
1 / 2 2 \ 3 3
算法分析:
通过递归,判定节点的左右节点是否相等。
AC代码:
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution { public boolean isSymmetric(TreeNode root) { if(root==null) return true; return isSym(root.left,root.right); } public boolean isSym(TreeNode left,TreeNode right) { if(left==null && right==null) return true; if(left!=null && right==null) return false; if(left==null && right!=null) return false; if(left.val!=right.val) return false; else return isSym(left.right,right.left)&&isSym(left.left,right.right); } }</span>
版权声明:本文为博主原创文章,转载注明出处
时间: 2024-12-22 10:53:04