0
点赞
收藏
分享

微信扫一扫

Day51 对称二叉树

给定一个二叉树,检查它是否是镜像对称的

https://leetcode-cn.com/problems/symmetric-tree/

二叉树 [1,2,2,3,4,4,3] 是对称的。

 1

/
2 2
/ \ /
3 4 4 3

[1,2,2,null,3,null,3] 则不是镜像对称的:

1

/
2 2
\
3 3

Java解法

package sj.shimmer.algorithm.m3_2021;

import java.util.ArrayList;
import java.util.List;

import sj.shimmer.algorithm.TreeNode;

/**
 * Created by SJ on 2021/3/17.
 */

class D51 {
    public static void main(String[] args) {
        System.out.println(isSymmetric(TreeNode.getInstance(new Integer[]{1,2,2,3,4,4,3})));
        System.out.println(isSymmetric(TreeNode.getInstance(new Integer[]{1,2,2,null,3,null,3})));
    }
    public static boolean isSymmetric(TreeNode root) {
        List<TreeNode> treeNodeList = new ArrayList<>();
        if (root != null) {
            treeNodeList.add(root.left);
            treeNodeList.add(root.right);
          return check(treeNodeList);
        }else {
            return true;
        }
    }
    public static boolean check(List<TreeNode> treeNodeList) {
        //转换为List数组
        List<TreeNode> temp = new ArrayList<>();
        int size = treeNodeList.size();
        boolean isEmpty = true;
        for (int i = 0; i < size; i++) {
            //第index层的父层 数量为index个;所以比较 index/2前后是否一致
            if (i>size/2){//已对比完成,直接加入
                if (treeNodeList.get(i)==null) {
                    temp.add(null);
                    temp.add(null);
                }else {
                    isEmpty = false;
                    temp.add(treeNodeList.get(i).left);
                    temp.add(treeNodeList.get(i).right);
                }
                continue;
            }
            if (treeNodeList.get(i) == null) {
                if (treeNodeList.get(size-1-i)==null){
                    temp.add(null);
                    temp.add(null);
                }else{
                    return false;
                }
            } else {
                if (treeNodeList.get(size - 1 - i) == null||treeNodeList.get(i).val != treeNodeList.get(size - 1 - i).val) {
                    return false;
                }
                isEmpty = false;
                temp.add(treeNodeList.get(i).left);
                temp.add(treeNodeList.get(i).right);
            }
        }
        if (isEmpty) {
            return true;
        }
        return check(temp);
    }
}

官方解

https://leetcode-cn.com/problems/symmetric-tree/solution/dui-cheng-er-cha-shu-by-leetcode-solution/

  1. 递归

    • 时间复杂度: O(n)
    • 空间复杂度: O(n)
  2. 迭代

    • 时间复杂度: O(n)
    • 空间复杂度: O(n)
举报

相关推荐

0 条评论