Загрузка...

Same Binary Tree Explained in 60 Seconds | LeetCode 100 | Java DSA Interview Question

Learn how to solve the Same Binary Tree problem (LeetCode 100) in just 60 seconds!

Given two binary trees, determine whether they are exactly the same.

For two trees to be considered identical:
✅ They must have the same structure
✅ They must contain the same node values

Example 1
Tree P Tree Q

1 1
/ \ / \
2 3 2 3
/ \ \ / \ \
4 5 6 4 5 6

Output: true

Example 2
Tree P Tree Q

1 1
/ \ / \
2 3 2 7
/ \ / \
4 5 4 5

Output: false

Java Recursive Solution
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}

if (p == null || q == null) {
return false;
}

if (p.val != q.val) {
return false;
}

return isSameTree(p.left, q.left) &&
isSameTree(p.right, q.right);
}

📌 Key Points:

Both nodes null → true
One node null → false
Values different → false
Recursively compare left and right subtrees

⏱️ Time Complexity: O(n)
💾 Space Complexity: O(h)

Subscribe for more Java, LeetCode, Binary Tree, and DSA interview preparation content!

Видео Same Binary Tree Explained in 60 Seconds | LeetCode 100 | Java DSA Interview Question канала EverythingAboutJava
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять