Subtree of Another Tree (LeetCode 572) | Full solution with examples | Study Algorithms

preview_player
Показать описание

Chapters:
00:00 - Intro
00:44 - Problem Statement and Description
02:27 - Efficient Solution
07:56 - Caveats and Gotchas
11:09 - Dry-run of Code
13:11 - Final Thoughts

📚 Links to topics I talk about in the video:

📖 Reference Books:

🎥 My Recording Gear:

💻 Get Social 💻

#leetcode #programming #interview
Рекомендации по теме
Комментарии
Автор

time complexity of this solution due to the .contains() func is going to be O(mn) i think, so you would think to use something better for string matching like KMP algo, the problem is kmp algorithm while in theory is O(m + n) which makes it linear in practice it is slower since there are no possible LPS (for lps u want same numbers but the value in nodes is distinct i think)which makes kmp perform like a bad version of naive so in practice its like 12ms in java compared to .contains function having 8ms in java.

Nikhil sir if you are reading this what can we do optimise this string matching more.

atharva
Автор

Whenever you put StringBuilder sb = new StringBuilder("^"); it passes the test cases but if you dont put the ^ it fails a single test case of root =[1, 2] and subroot=[2], can you explain why please? I think this is the same query that others trying to ask in the comment section

smridhjain
Автор

Only pre-Order traversal will work here, In other 2 (POT & IOT) all TCs will not pass

pratyushtripathy
Автор

class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {

if(root == null && subRoot == null) return true;

if(root == null) return false;

boolean isSame = false;

if(root.val == subRoot.val){
isSame = allsame(root, subRoot);
}

return isSame || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}

public boolean allsame(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 allsame(p.left, q.left) && allsame(p.right, q.right);
}
}

AniketGaikwad-hi
Автор

love ur explanion v much, , +1 suscription from my side buddy!!

mobile-alchemist
Автор

will fail only one test case. Anyways this method is not recommended, good explanation tho.

thor
visit shbcf.ru