对称的二叉树(JS)
对称的二叉树
http://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb
请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
首先:空二叉树为对称的
其次:可以先判断第二层是否有个为空有个不为空,直接返回false
然后就是一个先序遍历了,因为对称的话,左边的要对右边的,
1:从左树开始,如果节点存在则在字符串后插入它的节点值,节点为空则插入#
然后遍历它的左节点,再遍历他的右节点,最后返回一个左树的字符串
2:从右树开始,右树跟左树相似,主要是左树的是从左到右遍历,而右树需要从右到左遍历,这样才算是一个镜像对称。
/* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function isSymmetrical(pRoot) { // write code here if(pRoot == null) return true if((pRoot.left==null&&pRoot.right!=null) || (pRoot.right==null&&pRoot.left!=null)){ return false } let left = "", right = "" let LNode = pRoot.left,RNode = pRoot.right left = getNodeStr(LNode,left,0) right = getNodeStr(RNode,right,1) if(left == right) return true return false } function getNodeStr(root,str,k){ if(root === null){ str += "#" return str } str += root.val if(k==0){ str = getNodeStr(root.left,str,k) str = getNodeStr(root.right,str,k) } else{ str = getNodeStr(root.right,str,k) str = getNodeStr(root.left,str,k) } return str; } module.exports = { isSymmetrical : isSymmetrical };