101.对称二叉树

//1、递归
var
isSymmetric = function (root) { if (!root) return false; let flag = true; const rec = (left, right) => { if (left === null && right === null) { return; } if (left === null || right === null || left.val !== right.val) { flag = false; return; } rec(left.left, right.right); rec(left.right, right.left); }; rec(root.left, root.right); return flag; };
//2、迭代

var isSymmetric = function (root) { if (!root) return false; const stack = [root.left, root.right]; while (stack.length) { let p1 = stack.pop(); let p2 = stack.pop(); if (p1 === p2) continue; if (p1 && p2 && p1.val === p2.val) { stack.push(p1.left, p2.right, p1.right, p2.left); } else { return false; } } return true; };

  

 

 
posted @ 2021-07-26 15:57  jlin7  阅读(20)  评论(0)    收藏  举报