101 Symmetric Tree

判断一棵二叉树是否是自身的镜像

递归解决,faster than 22%

/**
 * 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 subSymmetric(root.left, root.right)
};
var subSymmetric = function(l, r){
    if (l === null && r === null) return true
    if (l === null || r === null) return false
    if (l.val !== r.val) return false
    return subSymmetric(l.left, r.right) && subSymmetric(l.right, r.left)
}

迭代实现,faster than 28%

var isSymmetric = function(root) {
    if (!root) return true
    var stack = []
    stack.push(root.left, root.right)
    while (stack.length){
        var l = stack.pop()
        var r = stack.pop()
        if(l === r) continue
        if(!l || !r || l.val !== r.val) return false
        stack.push(l.left, r.right)
        stack.push(l.right, r.left)
    }
    return true
};

你可能感兴趣的:(101 Symmetric Tree)