来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
解答
判断是否为对称二叉树,只能用层级遍历。然后收尾比对
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {boolean}*/var isSymmetric = function(root) {let stack = [ root ];while (stack.length) {let temp = [];for (let item of stack) {if (item) {temp.push(item.left);temp.push(item.right);}}stack = temp;if (stack.length) {let left = 0,right = stack.length - 1;while (left < right) {if (stack[left]?.val !== stack[right]?.val) {return false;}++left;--right;}}}return true;};
