January 16, 2024

Viiisit [LeetCode] - 101. Symmetric Tree

#php#javascript#ruby

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).

翻譯蒟蒻

判斷一個二元樹是否是自己的鏡像(以中心對稱,左子樹和右子樹是互相鏡像)。



Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
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