对称二叉树
递归写法
function help(root) { return isSymmetric(root, root); } function isSymmetric(node1, node2) { //判断两个节点都是否为空 if (!node1 && !node2) { return true; } //判断两个节点不相等 if (!node1 || !node2 || node1.val != node2.val) { return false; } return isSymmetric(node1.left, node2.right) && isSymmetric(node1.right, node2.left); }
非递归写法
function isSymmetric(root) { if(!root) return true const queue = [root.left, root.right] let node1, node2 while(queue.length) { node1 = queue.shift() node2 = queue.shift() if (!node1 && !node2) continue if (!node1 || !node2 || node1.val !== node2.val) return false //入队顺序,按照对称比对的顺序 queue.push(node1.left) queue.push(node2.right) queue.push(node1.right) queue.push(node2.left) } return true }