王廷瑋|數位醫療|智慧醫療: 100. Same Tree WFU

2024年7月5日 星期五

100. Same Tree

100. Same Tree


給定兩個二元樹的根節點 p 和 q,編寫一個函數來檢查它們是否相同。

如果兩個二元樹在結構上完全相同,且節點具有相同的值,則認為它們是相同的。

範例:

輸入:p = [1,2,3], q = [1,2,3] 輸出:true

這表明給定的兩棵二元樹 p 和 q 在結構上和節點值上完全相同,因此返回結果為真(true)。


Python


class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
# If both nodes are None, they're the same
if p is None and q is None:
return True
# If one is None and the other isn't, they're different
if p is None or q is None:
return False
# Check if the current node values are the same
if p.val != q.val:
return False
# Recursively check left and right subtrees
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

16.62MB, 32ms


C++


class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
// If both nodes are null, they're the same
if (p == nullptr && q == nullptr) {
return true;
}
// If one is null and the other isn't, they're different
if (p == nullptr || q == nullptr) {
return false;
}
// Check if the current node values are the same
if (p->val != q->val) {
return false;
}
// Recursively check left and right subtrees
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};

11.71MB, 2ms


Javascript


/**
* 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 both nodes are null, they're the same
if (p === null && q === null) {
return true;
}
// If one is null and the other isn't, they're different
if (p === null || q === null) {
return false;
}
// Check if the current node values are the same
if (p.val !== q.val) {
return false;
}
// Recursively check left and right subtrees
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};

49.34MB, 58ms