Same Binary Tree - Leetcode 100 - Trees (Python)

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


Please check my playlists for free DSA problem solutions:

My Favorite Courses:

Data Structures & Algorithms:

Python:

Web Dev / Full Stack:

Cloud Development:

Game Development:

SQL & Data Science:

Machine Learning & AI:
Рекомендации по теме
Комментарии
Автор

Master Data Structures & Algorithms For FREE at AlgoMap.io!

GregHogg
Автор

Hey Greg, the URL for this video on your AlgoMap site is broken

ChespinisEpic
Автор

why do we need a helper function here? We can build the same thing with the global function?

KıssadanHisseAmerika
Автор

nice! second condition can be simplified to `if not p or not q`

adrianodramisino
Автор

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)

rollbacked
Автор

Can someone explain why not use bfs in this case ?

theomichel
Автор

Title should be 'Same Tree' and not 'Same Binary Tree'.

soacm
Автор

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) )
};

shreyageek
join shbcf.ru