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

给你一个二叉树的根节点 root , 检查它是否轴对称。

解答

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