100. Same Tree
Il testo del problema è tradotto dal russo per la lingua selezionata. Il codice resta invariato.
given корни двух бинарных деревьев p и q. Напишите функцию, чтобы проверить, одинаковы ли они.
Два бинарных дерева считаются одинаковыми, если они структурно идентичны, и узлы имеют одинаковые значения.
Esempio:
Input: p = [1,2,3], q = [1,2,3]
Output: true
C# soluzione
abbinato/originalepublic class Solution {
public bool IsSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null)
return true;
if (q == null || p == null)
return false;
if (p.val != q.val)
return false;
return IsSameTree(p.right, q.right) && IsSameTree(p.left, q.left);
}
}
C++ soluzione
bozza automatica, rivedere prima dell'invio#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public bool IsSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null)
return true;
if (q == null || p == null)
return false;
if (p.val != q.val)
return false;
return IsSameTree(p.right, q.right) && IsSameTree(p.left, q.left);
}
}
Java soluzione
abbinato/originaleclass Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (q == null || p == null) return false;
if (p.val != q.val) return false;
return isSameTree(p.right, q.right) && isSameTree(p.left, q.left);
}
}
JavaScript soluzione
abbinato/originalevar isSameTree = function (p, q) {
if (p == null && q == null) return true;
if (q == null || p == null) return false;
if (p.val != q.val) return false;
return isSameTree(p.right, q.right) && isSameTree(p.left, q.left);
};
Python soluzione
abbinato/originaleclass Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if not q or not p:
return False
if p.val != q.val:
return False
return self.isSameTree(p.right, q.right) and self.isSameTree(
p.left, q.left
)
Go soluzione
abbinato/originaletype TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func isSameTree(p *TreeNode, q *TreeNode) bool {
if p == nil && q == nil {
return true
}
if p == nil || q == nil {
return false
}
if p.Val != q.Val {
return false
}
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
}
Algorithm
Самая простая стратегия здесь — использовать рекурсию. Проверьте, не равны ли узлы p и q значению None, и равны ли их значения. Если все проверки пройдены успешно, проделайте то же самое для дочерних узлов рекурсивно.
😎
Vacancies for this task
offerte attive with overlapping task tags are mostrati.
Non ci sono ancora offerte attive.