Same Binary Tree - Leetcode 100 - Trees (Python)

  Рет қаралды 3,523

Greg Hogg

Greg Hogg

Күн бұрын

Пікірлер: 7
@GregHogg
@GregHogg 4 ай бұрын
Master Data Structures & Algorithms For FREE at AlgoMap.io!
@wallwall3140
@wallwall3140 4 ай бұрын
u deserve a medal 🥇 thanks a lot
@shreyageek
@shreyageek 3 ай бұрын
this also works for all test cases without defining additional function var isSameTree = function(p, q) { if(!p && !q) return true; if(p&& !q || q &&!p) return false; if(p.val != q.val) return false; return (isSameTree(p.left,q.left) && isSameTree(p.right , q.right) ) };
@theomichel8405
@theomichel8405 5 ай бұрын
Can someone explain why not use bfs in this case ?
@boiledtoenail
@boiledtoenail 3 ай бұрын
Someone correct me if im wrong but recursive calls make it dfs in general due to it being a call stack (FIFO) and all that.
@Infinitely16
@Infinitely16 2 ай бұрын
You could do a BFS solution. The point is the visit all nodes in both trees at the same time. Both BFS and DFS accomplish this. DFS is just a preference.
@rollbacked
@rollbacked Ай бұрын
damn my solution was not that smart, I did a dfs helper function (doing it explicitly w/ a stack) that returned a visited array and did a comparison function dfs(p) == dfs(q) to check if the two trees were the same class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: def dfs(node): stack = [node] visited = [] while stack: curr_node = stack.pop() if curr_node: visited.append(curr_node.val) stack.append(curr_node.left) stack.append(curr_node.right) if curr_node is None: visited.append('null') # trees are equal if they have the same null values too return visited return dfs(p) == dfs(q)
Symmetric Tree - Leetcode 101 - Trees (Python)
4:16
Greg Hogg
Рет қаралды 2,5 М.
Rotting Oranges - Leetcode 994 - Graphs (Python)
16:09
Greg Hogg
Рет қаралды 3,4 М.
How Much Tape To Stop A Lamborghini?
00:15
MrBeast
Рет қаралды 210 МЛН
Ice Cream or Surprise Trip Around the World?
00:31
Hungry FAM
Рет қаралды 21 МЛН
When Cucumbers Meet PVC Pipe The Results Are Wild! 🤭
00:44
Crafty Buddy
Рет қаралды 57 МЛН
ТЫ В ДЕТСТВЕ КОГДА ВЫПАЛ ЗУБ😂#shorts
00:59
BATEK_OFFICIAL
Рет қаралды 4,5 МЛН
Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
20:30
Top 7 Algorithms for Coding Interviews Explained SIMPLY
21:22
Codebagel
Рет қаралды 442 М.
Diameter of Binary Tree - Leetcode 543 - Trees (Python)
11:16
Same Tree - Leetcode 100 - Python
7:52
NeetCode
Рет қаралды 130 М.
The Truth About Learning Python in 2024
9:38
Internet Made Coder
Рет қаралды 215 М.
Coin Change - Leetcode 322 - Dynamic Programming (Python)
15:27
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 147 М.
Exploratory Data Analysis with Pandas Python
40:22
Rob Mulla
Рет қаралды 500 М.
How Much Tape To Stop A Lamborghini?
00:15
MrBeast
Рет қаралды 210 МЛН