迭代解法
逐层遍历二叉树,得到当前层的节点后头尾互查做比较。做法比较直接
function isSymmetric( root ) { // write code here if(root==null) return true let cur_lvl = [root] while(cur_lvl.length>0){ for(let i=0;i<Math.floor(cur_lvl.length/2);i++){ //判断是否对称 if(cur_lvl[i]==null &&cur_lvl[cur_lvl.length-1-i]==null) continue if(cur_lvl[i]==null || cur_lvl[cur_lvl.length-1-i]==null||cur_lvl[i].val !== cur_lvl[cur_lvl.length-1-i].val) return false } cur_lvl = next_lvl(cur_lvl) console.log(cur_lvl.length) if(cur_lvl.length%2!==0) return false//长度必须为偶数。 } return true } function next_lvl(arr){//返回下一行的节点 let nxt_lvl = [] for(let item of arr){ if(item!==null){ nxt_lvl.push(item.left); nxt_lvl.push(item.right) } } return nxt_lvl }
递归解法
找到中心对称的节点对,相互比较。
function isSymmetric( root ) { if(!root) return true return symmetric( root.left,root.right) } function symmetric( leftNode,rightNode ) { if(!leftNode&&!rightNode) return true if(leftNode==null || rightNode==null || leftNode.val!==rightNode.val){ return false } return symmetric(leftNode.right,rightNode.left)&&symmetric(leftNode.left,rightNode.right) }