题目地址 https://leetcode-cn.com/problems/symmetric-tree/

1.递归

本题最简单的思路是递归,可以假设两棵一模一样的树在进行镜像对比。他们之间的关系满足node1.left == node2.rightnode1.right == node2.left
时间复杂度O(n) n为节点的个数;空间复杂度O(h) h为二叉树的最大深度

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return mirror(root, root);
    }
    private boolean mirror(TreeNode node1, TreeNode node2) {
        if (node1 == null && node2 == null) return true;
        if (node1 == null || node2 == null) return false;
        return node1.val == node2.val
            && mirror(node1.left, node2.right)
            && mirror(node2.left, node1.right);
    }
}

2.BFS

广度优先搜索思路还是和递归一样,假设是两棵一模一样的树在进行镜像对比。时间复杂度O(n) 空间复杂度O(n)

public boolean isSymmetric(TreeNode root) {
  Queue<TreeNode> q = new LinkedList<>();
  q.add(root);
  q.add(root);
  while (!q.isEmpty()) {
      TreeNode t1 = q.poll();
      TreeNode t2 = q.poll();
      if (t1 == null && t2 == null) continue;
      if (t1 == null || t2 == null) return false;
      if (t1.val != t2.val) return false;
      q.add(t1.left);
      q.add(t2.right);
      q.add(t1.right);
      q.add(t2.left);
  }
  return true;
}

java版本

class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null)
            return true;
        queue.offer(root);
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode node1 = queue.poll();
            TreeNode node2 = queue.poll();
            if (node1 == null && node2 == null)
                continue;
            if (node1 == null || node2 == null)
                return false;
            if (node1.val != node2.val)
                return false;
            queue.offer(node1.left);
            queue.offer(node2.right);
            queue.offer(node1.right);
            queue.offer(node2.left);
        }
        return true;
    }
}

更多LeetCode题解和数据结构方面的内容,可以关注我的github,求个star~ ▄█▔▉●


lznism
209 声望2 粉丝

我的github:[链接]