Leaf-Similar Trees - Leetcode 872 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·2y ago

Key Takeaways

The video solves the Leaf-Similar Trees problem on LeetCode using a recursive Depth-First Search (DFS) approach in Python, comparing the leaf node sequences of two binary trees.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem Leaf similar trees we're given the root of two binary trees and we want to know if they are Leaf similar to each other which really just means if you take every leaf node which by the way a leaf node in a tree is just a node that doesn't have any children so of course every tree has to have some Leaf nodes because otherwise they would be like never ending it'd be like infinite or something so we take the sequence of leaf nodes in the first string and when we say sequence we mean from left to right so six 7 4 9 8 that's the sequence and we do the same thing for the right sub tree as well 6 7 4 9 8 and we want to know are these two sequences equal to each other in this case they are so we return true if they're not we return false so the problem is pretty simple now how exactly do we get these sequences so given a tree the main problem we have is how do we get the Leaf sequence because if we can do that then we can easily compare between the two trees and solve the problem well when it comes to trees how many ways do you even know to Traverse a tree there are variations but the main two ways breath for search and depth for search at first you might think that breath for search would work but it's actually more tricky than you might think let's quickly walk through it BFS otherwise known as level order traversal basically goes through every level of the tree which at first seems like it would work we'd get these nodes 674 and by the way we would know that these are nodes that we're going to add to the leaf similar sequence because these are the nodes that don't have any children so we'd go from left to right left to right and then here left to right add each of these cuz they don't have children then get to two it does have children so don't add it and then we'd get these two as well so this is like the leaf sequence we could do the same thing for the left tree and this time though we'd see Okay add six to the leaf sequence then get to two then add 9 and8 to the sequence and then lastly we'd add these two so basically with breath for search we don't guarantee that all of the leaf nodes are on the same level so the order gets kind of messed up if we try to process it that way so this is how we kind of narrow it down and we go with depth for search which does work pretty easily the idea here is pretty much the same we're going to start at the root of a tree go left and then right and every time with depth for search we know we just keep going left until we can't go left anymore so from here we'd go down here and this time we do the same thing if we get to a leaf node we'd add it to the result so right now we'd have six then we'd go back back up to the parent and then here we'd go down to seven add seven then go back up to the parent and now start doing the right side of the tree so this way you can already kind of tell we will guarantee that we will reach each of these Leaf nodes from left to right with recursive depth for search so now we go to one then we go left to four add four to the result then go back up we're at two then go left this is a leaf node add it to the result nine then go back down right and add eight we can do the same thing with this tree I'll quickly do that so here we go left not a leaf node here we go left again six it's a leaf node go back up go right at two down to seven it's a leaf node add it go back up two now down to four it's also a leaf node and then we go all the way back up to the root and now we're at one go left add nine and lastly go back up and add eight so this way it's okay if the leaf nodes are on different levels of the tree we can still get the outputs pretty easily and once we have these we can pretty much just compare these two arrays if they are equal we can return true otherwise we return false doing this type of traversal on each of these trees will require us visiting every node let's say the size of the first tree is n and the size of the second tree is M we would take both of them together and add them up for the time complexity for the space complexity we will say the height of the first tree let's say that's H1 and H2 is the height of the second tree because we will need that for the recursive call stack but actually now that I think of it we will have to add each of the levels of each tree into an array if we want to do the comparison so in the worst case actually the memory complexity also becomes n + m you might be wondering why is that well the last level of a tree if it's a complete binary tree ends up being half the size of the entire tree which this is a linear so that's how I'm getting the same thing for the memory complexity now let's code it up so I'm going to first write our recursive DFS we will pass in the root of a single node and we will pass in a second variable which is going to be a array and we're going to be populating that array from within this function so before we even Implement DFS let me just show you what we're going to do we're going to have Leaf one leaf 2 these are both going to be empty arrays initially each of them is corresponding to one of the trees and we will call DFS from Route One and pass in leaf one do the same thing for the second tree and pass in leaf two and then at the end in Python we can simply compare arrays like this we can literally just do the equality operator if they're both the same we return true if not it'll be false so now the only thing left to do is implement this DFS which will populate each of these arrays so first is the base case with trees it's usually the same if we have an empty tree let's just return okay the other case is also important to us if we reach a leaf node so if not root. left and not root. right we also return because it's a leaf node we don't need to go any further but before we do that let's add this node the value of the node in particular to the array that's passed in okay otherwise what we do is just call DFS on the left subtree passing in leaf and call DFS on the right subtree also passing and leave this is the entire code let's run it to make sure that it works okay unfortunately I made a dumb mistake and did not put the knot in front of this that's when the tree is actually empty otherwise we're always going to be returning sorry about that that's my bad now let's rerun this as you can see on the left it works and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🧑‍💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/ 🐦 Twitter: https://twitter.com/neetcode1 ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf Problem Link: https://leetcode.com/problems/leaf-similar-trees/ 0:00 - Read the problem 1:14 - Drawing Explanation 5:06 - Coding Explanation leetcode 872 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

The video teaches how to solve the Leaf-Similar Trees problem using recursive DFS in Python, covering tree traversal and binary tree concepts.

Key Takeaways
  1. Define the problem and understand the concept of leaf-similar trees
  2. Choose a suitable tree traversal approach (DFS or BFS)
  3. Implement recursive DFS to traverse the binary trees and collect leaf node sequences
  4. Compare the leaf node sequences of the two trees
  5. Return true if the sequences are equal, false otherwise
💡 Recursive DFS is a suitable approach for traversing binary trees and collecting leaf node sequences, allowing for efficient comparison of leaf-similar trees.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python

Chapters (3)

Read the problem
1:14 Drawing Explanation
5:06 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →