keep learning, keep coding!
Problem - Symmetric Tree
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
翻譯蒟蒻
判斷一個二元樹是否是自己的鏡像(以中心對稱,左子樹和右子樹是互相鏡像)。
Example 1:
1 2
| Input: root = [1,2,2,3,4,4,3] Output: true
|
Example 2:
1 2
| Input: root = [1,2,2,null,3,null,3] Output: false
|
Solution - JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
var isSymmetric = function(root) { if (root === null) return true; return isMirror(root.left, root.right);
function isMirror(left, right) { if (left === null && right === null) return true; if (left === null || right === null) return false; return (left.val === right.val) && isMirror(left.left, right.right) && isMirror(left.right, right.left); } };
|
Solution - Ruby
1 2 3 4 5 6 7 8 9 10 11
| def is_mirror(left, right) return true if left.nil? && right.nil? return false if left.nil? || right.nil? return false if left.val != right.val return is_mirror(left.left, right.right) && is_mirror(left.right, right.left) end
def is_symmetric(root) return true if root.nil? return is_mirror(root.left, root.right) end
|
Solution - PHP
1 2 3 4 5 6 7 8 9 10
| function isMirror($left, $right) { if ($left == null && $right == null) return true; if ($left == null || $right == null) return false; return $left->val == $right->val && $this->isMirror($left->left, $right->right) && $this->isMirror($left->right, $right->left); }
function isSymmetric($root) { if ($root == null) return true; return $this->isMirror($root->left, $root->right); }
|
LeetCode 傳送門 - Symmetric Tree