101.对称二叉树

题目

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

例如,二叉树 [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

进阶:

  • 你可以运用递归和迭代两种方法解决这个问题吗?

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/symmetric-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

JS实现

1、递归实现

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
const check = (p, q) => {
  if (!p && !q) {
    return true;
  }
  if (!p || !q) {
    return false;
  }
  return p.val === q.val && check(p.left, q.right) && check(p.right, q.left);
};
var isSymmetric = function (root) {
  return check(root, root);
};

2、迭代实现

const check = (u, v) => {
  const q = [];
  q.push(u);
  q.push(v);

  while (q.length) {
    u = q.shift();
    v = q.shift();

    if (!u && !v) {
      continue;
    }
    if (!u || !v || u.val !== v.val) {
      return false;
    }

    q.push(u.left);
    q.push(v.right);

    q.push(u.right);
    q.push(v.left);
  }
  return true;
};
var isSymmetric = function (root) {
  return check(root, root);
};

Go实现

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func check(node1 *TreeNode, node2 *TreeNode) bool {
  if node1 == nil && node2 == nil {
    return true
  }
  if node1 == nil || node2 == nil {
    return false
  }
  return node1.Val == node2.Val && check(node1.Left, node2.Right) && check(node1.Right, node2.Left)
}
func isSymmetric(root *TreeNode) bool {
  return check(root, root)
}