Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

对称二叉树 #22

Open
JesseZhao1990 opened this issue Jul 2, 2018 · 0 comments
Open

对称二叉树 #22

JesseZhao1990 opened this issue Jul 2, 2018 · 0 comments

Comments

@JesseZhao1990
Copy link
Owner

image

/**
 * 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同样相等。以此递归下去。

题中的二叉树画的层次有点浅,我画了一个层次稍微深一点的。可以在脑子里过一遍,对于下图是怎么递归比较的。

image

leetcode 原题地址: https://leetcode-cn.com/problems/symmetric-tree/description/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant