Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1/ \2 2/ \ / \3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1/ \2 2\ \3 3
Follow up: Solve it both recursively and iteratively.
解法一: 递归解法。
/*** 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 isMirror(root.left, root.right)};function isMirror(leftNode, rightNode) {if (leftNode === null && rightNode === null) {return true}if (leftNode === null || rightNode === null) {return false}if (leftNode.val === rightNode.val) {return isMirror(leftNode.left, rightNode.right) && isMirror(leftNode.right, rightNode.left)} else {return false}}
解法二: 迭代解法:
1/ \2 2/ \ / \3 4 4 3/ \ / \ / \ / \5 6 7 8 8 7 6 5
解析:
stack = [2, 2];[2, 2], 推入 [3, 3, 4, 4];[4, 4], 推入 [7, 7, 8, 8];[8, 8];[7, 7], 取出 [3, 3];[5, 5, 6, 6];[6, 6];[5, 5];/*** 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) return trueif (!root.left && !root.right) return trueif (root.left && root.right && root.left.val !== root.right.val) return falseconst stack = []stack.push(root.right)stack.push(root.left)while (stack.length > 0) {const popItemLeft = stack.pop()const popItemRight = stack.pop()if (!popItemLeft && !popItemRight) continueif (!popItemLeft || !popItemRight || popItemLeft.val !== popItemRight.val) return falsestack.push(popItemRight.right, popItemLeft.left, popItemRight.left, popItemLeft.right)}return true};