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 М.
Diameter of Binary Tree - Leetcode 543 - Trees (Python)
11:16
When Cucumbers Meet PVC Pipe The Results Are Wild! 🤭
00:44
Crafty Buddy
Рет қаралды 57 МЛН
Same Tree - Leetcode 100 - Python
7:52
NeetCode
Рет қаралды 130 М.
Rotting Oranges - Leetcode 994 - Graphs (Python)
16:09
Greg Hogg
Рет қаралды 3,4 М.
The Truth About Learning Python in 2024
9:38
Internet Made Coder
Рет қаралды 215 М.
Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
20:30
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 147 М.
Binary Search Tree in Python
22:59
NeuralNine
Рет қаралды 54 М.
Coin Change - Leetcode 322 - Dynamic Programming (Python)
15:27
Symmetric Tree - Leetcode 101 - Python
6:40
NeetCodeIO
Рет қаралды 39 М.
Clone Graph - Leetcode 133 - Graphs (Python)
13:38
Greg Hogg
Рет қаралды 3,8 М.