对称二叉树
JesseZhao1990 opened this issue · 0 comments
JesseZhao1990 commented
/**
* 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) {
if(root == null){
return true;
}
return symmetric(root.left,root.right);
};
function symmetric(node1,node2){
if(node1 === null || node2 === null){
return node1 === node2
}
return (node1.val === node2.val) && symmetric(node1.left,node2.right) && symmetric(node1.right,node2.left);
}
解题思路,对于每两个相比较的节点node1和node2。node1的左节点和node2的右节点比较,node1的右节点和node2的左节点比较。如果满足三个条件,则两个节点是对称的。三个条件为为node1和node2 的值相等,node1.left 和node2.right同样相等,node1.right和node2.left同样相等。以此递归下去。
题中的二叉树画的层次有点浅,我画了一个层次稍微深一点的。可以在脑子里过一遍,对于下图是怎么递归比较的。
leetcode 原题地址: https://leetcode-cn.com/problems/symmetric-tree/description/

