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

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

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

解答

判断是否为对称二叉树,只能用层级遍历。然后收尾比对

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {boolean}
  11. */
  12. var isSymmetric = function(root) {
  13. let stack = [ root ];
  14. while (stack.length) {
  15. let temp = [];
  16. for (let item of stack) {
  17. if (item) {
  18. temp.push(item.left);
  19. temp.push(item.right);
  20. }
  21. }
  22. stack = temp;
  23. if (stack.length) {
  24. let left = 0,
  25. right = stack.length - 1;
  26. while (left < right) {
  27. if (stack[left]?.val !== stack[right]?.val) {
  28. return false;
  29. }
  30. ++left;
  31. --right;
  32. }
  33. }
  34. }
  35. return true;
  36. };