问题
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
解决
class Solution {
public boolean isSymmetric (TreeNode root) {
if (root==null ) return true ;
return check(root,root);
}
public boolean check (TreeNode r1,TreeNode r2) {
if (r1==null &&r2==null ) return true ;
if (r1==null ||r2==null ) return false ;
return r1.val==r2.val&&check(r1.left,r2.right)&&check(r1.right,r2.left);
}
}
递归的时间复杂度和空间复杂度
class Solution {
public boolean isSymmetric (TreeNode root) {
return check(root, root);
}
public boolean check (TreeNode u, TreeNode v) {
Queue<TreeNode> q = new LinkedList <TreeNode>();
q.offer(u);
q.offer(v);
while (!q.isEmpty()) {
u = q.poll();
v = q.poll();
if (u == null && v == null ) {
continue ;
}
if ((u == null || v == null ) || (u.val != v.val)) {
return false ;
}
q.offer(u.left);
q.offer(v.right);
q.offer(u.right);
q.offer(v.left);
}
return true ;
}
}
迭代的时间复杂度和空间复杂度
class Solution {
public boolean isSymmetric (TreeNode root) {
if (root==null ) return true ;
TreeNode curroot=cloneTree(root);
TreeNode newroot=isSymmetricCopy(curroot);
return check(root,newroot);
}
public TreeNode isSymmetricCopy (TreeNode root) {
if (root==null ) return root;
TreeNode left=isSymmetricCopy(root.left);
TreeNode right=isSymmetricCopy(root.right);
root.left=right;
root.right=left;
return root;
}
public boolean check (TreeNode root,TreeNode newroot) {
if (root == null && newroot == null ) {
return true ;
}
if (root == null || newroot == null ) {
return false ;
}
return check(root.left,newroot.left)&&check(root.right,newroot.right)&&root.val==newroot.val;
}
public TreeNode cloneTree (TreeNode root) {
TreeNode node=null ;
if (root==null ) return null ;
node=new TreeNode (root.val);
node.left=cloneTree(root.left);
node.right=cloneTree(root.right);
return node;
}
}
方法三的时间复杂度和空间复杂度:O(N) O(N),但是常数上有区别
class Solution {
public boolean isSymmetric (TreeNode root) {
if (root==null ) return true ;
ArrayList r1=new ArrayList <>();
ArrayList r2=new ArrayList <>();
ArrayList l1= preOrderRecur(root,r1);
int size=r1.size();
TreeNode newroot=isSymmetricCopy(root);
ArrayList l2=preOrderRecur(newroot,r2);
for (int i = 0 ; i < size; i++) {
if (l1.get(i) != l2.get(i)) {
return false ;
}
}
return true ;
}
public static TreeNode isSymmetricCopy (TreeNode root) {
if (root==null ) return root;
TreeNode left=isSymmetricCopy(root.left);
TreeNode right=isSymmetricCopy(root.right);
root.left=right;
root.right=left;
return root;
}
public static ArrayList preOrderRecur (TreeNode root, ArrayList list) {
if (root == null ) {
return list;
}
list.add(root.val);
preOrderRecur(root.left,list);
preOrderRecur(root.right,list);
return list;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了