数据结构与算法

Leetcode 101 对称二叉树

2021-12-19  本文已影响0人  itbird01

101. 对称二叉树

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

解题思路

解法1:--超出时间限制
1.层序遍历,结果数组List<List<Integer>> result
2.对比每一层的数据,是否是左右对称
解法2:
1.双指针方法,一个指针在左端,一个指针在右端
2.用递归的方法,判断左指针的left== 右指针的right && 左指针的right == 右指针的left && 左指针的val == 右指针的val

解题遇到的问题

后续需要总结学习的知识点

##解法1--超出时间限制
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class Solution {
    public boolean isSymmetric(TreeNode root) {
        List<List<Integer>> reList = levelOrder(root);
        for (int i = 0; i < reList.size(); i++) {
            List<Integer> rIntegers = reList.get(i);
            int l = 0, r = rIntegers.size() - 1;
            while (l < r) {
                if (rIntegers.get(l) != rIntegers.get(r)) {
                    return false;
                } else {
                    l++;
                    r--;
                }
            }
        }
        return true;
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ansList = new ArrayList<List<Integer>>();
        if (root == null) {
            return ansList;
        }

        LinkedList<TreeNode> linkedList = new LinkedList<TreeNode>();
        linkedList.add(root);
        while (!linkedList.isEmpty()) {
            List<Integer> temp = new ArrayList<Integer>();
            LinkedList<TreeNode> tenmpLinkedList = new LinkedList<TreeNode>();
            for (int i = 0; i < linkedList.size(); i++) {
                temp.add(linkedList.get(i).val);
                if (linkedList.get(i).left != null) {
                    tenmpLinkedList.add(linkedList.get(i).left);
                } else {
                    tenmpLinkedList.add(new TreeNode(0));
                }
                if (linkedList.get(i).right != null) {
                    tenmpLinkedList.add(linkedList.get(i).right);
                } else {
                    tenmpLinkedList.add(new TreeNode(0));
                }
            }
            ansList.add(temp);
            linkedList.clear();
            linkedList.addAll(tenmpLinkedList);
        }
        return ansList;
    }

}

##解法2
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return false;
        }
        return isSymmetric(root.left, root.right);
    }

    private boolean isSymmetric(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        }

        if (left == null || right == null) {
            return false;
        }

        return left.val == right.val && isSymmetric(left.left, right.right)
                && isSymmetric(left.right, right.left);
    }
}
上一篇下一篇

猜你喜欢

热点阅读