January 12, 2024

Viiisit [LeetCode] - 100. Same Tree

#php#javascript#ruby

keep learning, keep coding!

Problem - Same Tree

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

翻譯蒟蒻

比較兩個二元樹是否相同。也就是需要比較他們的結構和每個對應節點的值是否相等。



Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 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} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};

Solution - Ruby

1
2
3
4
5
def is_same_tree(p, q)
return true if p.nil? && q.nil?
return false if p.nil? || q.nil?
p.val == q.val && is_same_tree(p.left, q.left) && is_same_tree(p.right, q.right)
end

Solution - PHP

1
2
3
4
5
6
7
8
9
function isSameTree($p, $q) {
if ($p == null && $q == null) {
return true;
}
if ($p == null || $q == null) {
return false;
}
return $p->val == $q->val && $this->isSameTree($p->left, $q->left) && $this->isSameTree($p->right, $q->right);
}

LeetCode 傳送門 - Same Tree