post_href
stringlengths
57
213
python_solutions
stringlengths
71
22.3k
slug
stringlengths
3
77
post_title
stringlengths
1
100
user
stringlengths
3
29
upvotes
int64
-20
1.2k
views
int64
0
60.9k
problem_title
stringlengths
3
77
number
int64
1
2.48k
acceptance
float64
0.14
0.91
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
https://leetcode.com/problems/longest-common-prefix/discuss/783976/Python-Simple-Solution-beats-100-runtime-12ms
class Solution(object): def longestCommonPrefix(self, strs): if len(strs) == 0: return "" return self.lcp_helper(min(strs), max(strs)) def lcp_helper(self, s1, s2): i = 0 while i<len(s1) and i<len(s2) and s1[i]==s2[i]: i += 1 return s1[:i]
longest-common-prefix
Python - Simple Solution, beats 100%, runtime 12ms
shaggy_x
13
1,600
longest common prefix
14
0.408
Easy
600
https://leetcode.com/problems/longest-common-prefix/discuss/2175545/Python-Solution-~-Beats-95.34-oror-Brute-Force
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: strs.sort() lim = min(strs,key=len) res = "" for i in range(len(lim)): if strs[0][i] != strs[len(strs)-1][i]: break res += strs[0][i] return res
longest-common-prefix
Python Solution ~ Beats 95.34% || Brute Force
Shivam_Raj_Sharma
12
949
longest common prefix
14
0.408
Easy
601
https://leetcode.com/problems/longest-common-prefix/discuss/2695808/Python-oror-Easy-to-Understand
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: strs.sort(key = lambda x:len(x)) prefix = strs[0] for i in range(len(strs[0]),0,-1): if all([prefix[:i] == strs[j][:i] for j in range(1,len(strs))]): return(prefix[:i]) return ""
longest-common-prefix
Python || Easy to Understand
sheshankkumarsingh28
11
4,000
longest common prefix
14
0.408
Easy
602
https://leetcode.com/problems/longest-common-prefix/discuss/2297953/Python-91.45-fasters-or-Python-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-String-or-O(n)
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: res = "" #Taking a empty string for saving the result for i in zip(*strs): # check out the bottom of this artical for its explanation. a = "".join(i) # joining the result of zip, check out the example if len(set(a)) != 1: # this will checkout, if the elements of the all the provided string on a same level (i.e a[i][i]) are identical or not. If its identical then will always be equal to one. return res else: res += a[0] # if we are having identical element in the string will add it to our resulting string. return res
longest-common-prefix
Python 91.45% fasters | Python Simplest Solution With Explanation | Beg to adv | String | O(n)
rlakshay14
11
901
longest common prefix
14
0.408
Easy
603
https://leetcode.com/problems/longest-common-prefix/discuss/2264602/Python-Faster-98
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: ans = '' for i,val in enumerate(zip(*strs)): if len(set(val)) == 1: ans+= val[0] else: break return ans
longest-common-prefix
Python Faster 98%
Abhi_009
10
859
longest common prefix
14
0.408
Easy
604
https://leetcode.com/problems/longest-common-prefix/discuss/404383/Python3%3A-short-expressive-and-fast-solution-(faster-than-99.73)
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: prefix = '' for cmbn in zip(*strs): if len(set(cmbn)) > 1: break prefix += cmbn[0] return prefix
longest-common-prefix
Python3: short, expressive and fast solution (faster than 99.73%)
nehochuha
10
1,900
longest common prefix
14
0.408
Easy
605
https://leetcode.com/problems/longest-common-prefix/discuss/2019053/Python-simplest-solution-in-O(nlog(n))
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: strs.sort() pre = [] for a,b in zip(strs[0], strs[-1]): if a == b: pre.append(a) else: break return "".join(pre)
longest-common-prefix
Python simplest solution in O(nlog(n))
Blank__
8
451
longest common prefix
14
0.408
Easy
606
https://leetcode.com/problems/longest-common-prefix/discuss/2163267/Python-beats-99.11-with-full-working-explanation
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: # Time: O(n*n) and Space: O(1) res='' for i in range(len(strs[0])): # we take the first string from the list of strings as the base case for s in strs: # taking one string at a time and checking each of the strings' character at the same index i if i==len(s) or s[i]!=strs[0][i]: # when anyone of the string reaches its end and at index i strings does not match return res # we cannot go ahead now as per the LCP rules, and we need to return the longest common prefix res+=strs[0][i] # when all the conditions in if fails for every string at index i, that means that character at i is LCP return res # when for loop exit, means the whole base case was the LCP
longest-common-prefix
Python beats 99.11% with full working explanation
DanishKhanbx
7
630
longest common prefix
14
0.408
Easy
607
https://leetcode.com/problems/longest-common-prefix/discuss/1507207/Simple-Python-Sorting-Solution
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: # sort the array and then compare the first and last string strs.sort() str_start = strs[0] str_last = strs[-1] count = 0 for i in range(len(str_start)): if (str_start[i] != str_last[i]): break else: count += 1 if count == 0: return "" else: return str_start[:count]
longest-common-prefix
Simple Python Sorting Solution
Shwetabh1
7
280
longest common prefix
14
0.408
Easy
608
https://leetcode.com/problems/longest-common-prefix/discuss/1563979/Simplest-oror.-python-oror-zip(*strs)-oror-beats-99
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: i=0 for s in zip(*strs): if len(set(s))!=1: break i+=1 return strs[0][0:i]
longest-common-prefix
Simplest ||. python || zip(*strs) || beats 99%
Blank__
6
454
longest common prefix
14
0.408
Easy
609
https://leetcode.com/problems/longest-common-prefix/discuss/1506982/Python-faster-than-99.81
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: cmn= strs[0] for i in strs: if len(i)<len(cmn): cmn=i n=len(cmn) while n: flag=0 for i in strs: if i[0:n]!=cmn: flag=1 break if flag==1: n-=1 cmn=cmn[0:n] else: return cmn return ""
longest-common-prefix
Python faster than 99.81%
Jyoti_Yadav
6
594
longest common prefix
14
0.408
Easy
610
https://leetcode.com/problems/longest-common-prefix/discuss/2773589/Efficient-Python-Solution
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: prefix = '' for p in range(len(strs[0])): for m in range(1, len(strs)): if p > len(strs[m])-1 or strs[m][p] != strs[0][p]: return prefix prefix += strs[0][p] return prefix
longest-common-prefix
Efficient Python Solution
really_cool_person
5
1,000
longest common prefix
14
0.408
Easy
611
https://leetcode.com/problems/longest-common-prefix/discuss/1789795/Beats-99.45-of-submissions-in-runtime.-You-are-probably-overthinking-it-unclear-instructions
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: result = "" strs.sort() # Loop over the characters in the first index of the array for char in range(len(strs[0])): #If the character is the same in both the first and last string at the same index, append to result and continue with the loop. if strs[0][char] == strs[-1][char]: result += strs[0][char] continue else: # Break out of the loop here. Personally, I find this this easier to read, could also just return the result. break return result
longest-common-prefix
Beats 99.45% of submissions in runtime. You are probably overthinking it - unclear instructions
Dranting
5
443
longest common prefix
14
0.408
Easy
612
https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/2790811/Python-solution
class Solution: def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: levels = [] def order(node, level): if level >= len(levels): levels.append([]) if node: levels[level].append(node.val) if node.left: order(node.left, level + 1) if node.right: order(node.right, level + 1) if not root: return [] order(root, 0) return levels
binary-tree-level-order-traversal
Python solution
maomao1010
0
3
binary tree level order traversal
102
0.634
Medium
613
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2098804/Python3-Clean-Solution-using-Queue-Level-Order-Traversal
class Solution: def zigzagLevelOrder(self, root): res = [] if not root: return res zigzag = True q = collections.deque() q.append(root) while q: n = len(q) nodesOfThisLevel = [] for i in range(n): node = q.popleft() nodesOfThisLevel.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) if zigzag: res.append(nodesOfThisLevel) zigzag = False else: res.append(nodesOfThisLevel[::-1]) zigzag = True return res # Time: O(N) # Space: O(N)
binary-tree-zigzag-level-order-traversal
[Python3] Clean Solution using Queue Level Order Traversal
samirpaul1
7
240
binary tree zigzag level order traversal
103
0.552
Medium
614
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2297364/Python-or-easy-understanding
class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if not root: return [] res = [] q = deque() q.append(root) switch = False #check if we need to reverse in that layer while q: tmp = [] for i in range(len(q)): node = q.popleft() tmp.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) if switch: # need to reverse the order in this layer tmp.reverse() res.append(tmp) # remember to turn on and off switch = not switch return res
binary-tree-zigzag-level-order-traversal
Python | easy-understanding
An_222
1
69
binary tree zigzag level order traversal
103
0.552
Medium
615
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/1307677/Modification-to-level-order-traversal
class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if root== None: return [] else: res = [] queue = [] queue.append(root) flag = True while queue: level = [] flag = -flag for _ in range(len(queue)): temp = queue.pop(0) level.append(temp.val) if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) if flag == True: level = level[::-1] res.append(level) return res
binary-tree-zigzag-level-order-traversal
Modification to level order traversal
asthaya1
1
56
binary tree zigzag level order traversal
103
0.552
Medium
616
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/1172484/Faster-than-97.13-python-solution-it-varies-based-on-test-cases
class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return d=[] l=[] d.append(root) p=0 direction=1 while d: q=len(d) l1=[] while q: i=d.pop(0) l1.append(i.val) if i.left: d.append(i.left) if i.right: d.append(i.right) q-=1 l.append((l1)[::direction]) direction=direction*-1 return l
binary-tree-zigzag-level-order-traversal
Faster than 97.13% python solution it varies based on test cases
lalith_kumaran
1
105
binary tree zigzag level order traversal
103
0.552
Medium
617
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2762341/Python3-deque-Sol.-faster-then-96
class Solution: def zigzagLevelOrder(self, root): res = [] if not root: return res zigzag = True q = collections.deque() q.append(root) while q: n = len(q) nodesOfThisLevel = [] for i in range(n): node = q.popleft() nodesOfThisLevel.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) if zigzag: res.append(nodesOfThisLevel) zigzag = False else: res.append(nodesOfThisLevel[::-1]) zigzag = True return res
binary-tree-zigzag-level-order-traversal
Python3 deque Sol. faster then 96%
pranjalmishra334
0
7
binary tree zigzag level order traversal
103
0.552
Medium
618
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2751260/Level-Order-Traversal-or-Deque-or-Easy-to-Understand-or-Python
class Solution(object): def zigzagLevelOrder(self, root): if not root: return [] ans, q, flag = [], deque(), False while q: temp = [] for _ in range(len(q)): p = q.popleft() temp.append(p.val) if p.left: q.append(p.left) if p.right: q.append(p.right) if flag: ans.append(temp[::-1]) else: ans.append(temp) flag = not(flag) return ans
binary-tree-zigzag-level-order-traversal
Level Order Traversal | Deque | Easy to Understand | Python
its_krish_here
0
5
binary tree zigzag level order traversal
103
0.552
Medium
619
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2735430/Python-O(n)-(92.34)-(No-Queue)-Divide-and-Conquer-Solution
class Solution: def zigzagLevelOrder(self, root): // based on dfs def divide_conquer(root, depth): if root is None: return {} // store root's value of this depth(level) small_answer = {} small_answer[depth] = [root.val] // divide current problem with left smaller problem and right smaller problem l = divide_conquer(root.left, depth + 1) r = divide_conquer(root.right, depth + 1) // get two parts that have been resolved conquered_level = depth + 1 conquered_l = l.get(conquered_level, []) conquered_r = r.get(conquered_level, []) // merge two parts by the rules while conquered_l != [] or conquered_r != []: if conquered_level % 2 == 0: small_answer[conquered_level] = conquered_r + conquered_l else: small_answer[conquered_level] = conquered_l + conquered_r conquered_level += 1 conquered_l = l.get(conquered_level, []) conquered_r = r.get(conquered_level, []) // and also this answer will be one part of the higher level return small_answer return divide_conquer(root, 1).values()
binary-tree-zigzag-level-order-traversal
🇰🇷 [Python] O(n) (92.34%) (No Queue) Divide and Conquer Solution
kwc8384
0
18
binary tree zigzag level order traversal
103
0.552
Medium
620
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2711498/Python-BFS-Beats-97-Simple-change
class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: stack = [root] final = [] div = 1 if(not(root)):return while(stack): temp, temp1 = [], [] for _ in range(len(stack)): value = stack.pop(0) temp1.append(value.val) if(value.left):temp.append(value.left) if(value.right):temp.append(value.right) stack = temp if(div % 2 == 0): final.append(temp1[::-1]) else: final.append(temp1) div += 1 return (final)
binary-tree-zigzag-level-order-traversal
Python BFS Beats 97% - Simple change
bhavesh0124
0
3
binary tree zigzag level order traversal
103
0.552
Medium
621
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2587621/Python-3-Super-easy-to-understand!
class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root is None: return [] level_values = dict() def bfs(node, level): if node is None: return if level not in level_values: level_values[level] = [] level_values[level].append(node.val) bfs(node.left, level + 1) bfs(node.right, level + 1) bfs(root, 0) max_level = max(level_values.keys()) zigzag = [] for pos, level in enumerate(range(max_level + 1)): level_data = level_values[level] if level % 2 == 1: # reversed row level_data = level_data[::-1] zigzag.append(level_data) return zigzag
binary-tree-zigzag-level-order-traversal
Python 3 Super easy to understand!
zakmatt
0
64
binary tree zigzag level order traversal
103
0.552
Medium
622
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2539758/python-20ms-solution-beats-90.
class Solution(object): def zigzagLevelOrder(self, root): if not root: return [] res=[] q=[root] z=True while q: qLen=len(q) level=[] for i in range(qLen): node=q.pop(0) level.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) if not z: res.append(level[::-1]) else: res.append(level) z=not z return res
binary-tree-zigzag-level-order-traversal
python 20ms solution beats 90%.
babashankarsn
0
33
binary tree zigzag level order traversal
103
0.552
Medium
623
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2534491/Simple-Python-Solution-oror-BFS
class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ans = [] cur_level, cur_level_nodes = 0, [] # initialise and add root in queue with level as 0 q = deque() q.append((root, 0)) while q: # get first element from the queue and its resp. level node, level = q.popleft() if node is None: continue # if level is same, append nodes value # else change level and append nodes value if level == cur_level: cur_level_nodes.append(node.val) else: # reverse the list if cur_level is even ans.append(cur_level_nodes[::(-1 if cur_level%2 else 1)]) cur_level = level cur_level_nodes = [node.val] # add left and right children in queue with level as parent's level + 1 q.append((node.left, level+1)) q.append((node.right, level+1)) if len(cur_level_nodes): ans.append(cur_level_nodes[::(-1 if cur_level%2 else 1)]) return ans
binary-tree-zigzag-level-order-traversal
🔥 Simple Python Solution || BFS
wilspi
0
24
binary tree zigzag level order traversal
103
0.552
Medium
624
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2458786/super-easy-solution-with-trick-and-comments-TC%3A-O(N)-SC-%3A-O(N)
class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: res = [] if(root == None): return res q = deque() q.append(root) check = True while(q): sz = len(q) curr = [] for i in range(sz): temp = q.popleft() curr.append(temp.val) if(temp.left): q.append(temp.left) if(temp.right): q.append(temp.right) if(check): res.append(curr) else: res.append(curr[::-1]) check = not check return res
binary-tree-zigzag-level-order-traversal
super easy solution with trick and comments TC: O(N) SC : O(N)
rajitkumarchauhan99
0
30
binary tree zigzag level order traversal
103
0.552
Medium
625
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2331857/simple-python-solution
class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: # Same as level order traversal, but here we use count to store levels # in alternate fashion # T(n)=O(n) def helper(root,res): if root is None: return q=deque() q.append(root) count=0 while q: count+=1 path=[] size=len(q) for _ in range(size): node=q.popleft() path+=[node.val] if node.left: q.append(node.left) if node.right: q.append(node.right) if count%2: res.append(path) else: res.append(path[::-1]) return res res=[] return helper(root,res)
binary-tree-zigzag-level-order-traversal
simple python solution
Aniket_liar07
0
35
binary tree zigzag level order traversal
103
0.552
Medium
626
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2106081/Simple-Python-BFS-Solution
class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if root == None: return [] else: direction=-1 q=[root] ans=[] while len(q)!=0: ans_temp=[] for i in range(len(q)): temp=q.pop(0) ans_temp.append(temp.val) if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) if direction == 1: ans.append(ans_temp[::-1]) direction = -1 else: ans.append(ans_temp) direction = 1 return ans
binary-tree-zigzag-level-order-traversal
Simple Python BFS Solution
utk61198
0
23
binary tree zigzag level order traversal
103
0.552
Medium
627
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2103369/Python-using-BFS
class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if not root: return root q = [root] level = [] res = [[root.val]] x = 0 while q and root: for node in q: if node.left: level.append(node.left) if node.right: level.append(node.right) temp = [] for i in level: temp.append(i.val) x += 1 if temp: if x % 2 != 0: res.append(temp[::-1]) else: res.append(temp) q = level level = [] return res
binary-tree-zigzag-level-order-traversal
Python using BFS
ankurbhambri
0
57
binary tree zigzag level order traversal
103
0.552
Medium
628
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1769367/Python3-RECURSIVE-DFS-(-**-)-Explained
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: def dfs(root, depth): if not root: return depth return max(dfs(root.left, depth + 1), dfs(root.right, depth + 1)) return dfs(root, 0)
maximum-depth-of-binary-tree
✔️ [Python3] RECURSIVE DFS ( •⌄• ू )✧, Explained
artod
140
21,400
maximum depth of binary tree
104
0.732
Easy
629
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/359949/Python-recursive-and-iterative-solution
class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
maximum-depth-of-binary-tree
Python recursive and iterative solution
amchoukir
219
18,300
maximum depth of binary tree
104
0.732
Easy
630
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2424930/Very-Easy-oror-100-oror-Fully-Explained-(C%2B%2B-Java-Python-JS-C-Python3)
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: # Base case... # If the subtree is empty i.e. root is NULL, return depth as 0... if root == None: return 0 # if root is not NULL, call the same function recursively for its left child and right child... # When the two child function return its depth... # Pick the maximum out of these two subtrees and return this value after adding 1 to it... return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 # Adding 1 is the current node which is the parent of the two subtrees...
maximum-depth-of-binary-tree
Very Easy || 100% || Fully Explained (C++, Java, Python, JS, C, Python3)
PratikSen07
10
617
maximum depth of binary tree
104
0.732
Easy
631
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/872098/Python3-simple-DFS-implementation-faster-than-98
class Solution: def maxDepth(self, node: TreeNode) -> int: if node is None: return 0 return max(self.maxDepth(node.left) + 1, self.maxDepth(node.right) + 1)
maximum-depth-of-binary-tree
Python3 simple DFS implementation, faster than 98%
n0execution
5
933
maximum depth of binary tree
104
0.732
Easy
632
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2172542/Python3-solution-using-DFS
class Solution: def maxDepth(self, root: TreeNode) -> int: if root==None: return 0 left = self.maxDepth(root.left) right = self.maxDepth(root.right) return max(left,right)+1
maximum-depth-of-binary-tree
📌 Python3 solution using DFS
Dark_wolf_jss
4
49
maximum depth of binary tree
104
0.732
Easy
633
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2008749/O(n)time-BEATS-99.97-3-LINES-MEMORYSPEED-0ms-MAY-2022
class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
maximum-depth-of-binary-tree
O(n)time / BEATS 99.97% / 3 LINES / MEMORY/SPEED 0ms MAY 2022
cucerdariancatalin
4
362
maximum depth of binary tree
104
0.732
Easy
634
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2684293/Python3-oror-Recursive-oror-DFS-oror-Well-Explained-oror-Buttom-up-Approach-oror-2-LIne-solution
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if root: if (not root.left and not root.right): return 1 left = right = 0 if (root.left): left = self.maxDepth(root.left) if (root.right): right = self.maxDepth(root.right) return 1+max(left,right) return 0
maximum-depth-of-binary-tree
Python3 || Recursive || DFS || Well Explained || Buttom up Approach || 2 LIne solution
NitishKumarVerma
3
278
maximum depth of binary tree
104
0.732
Easy
635
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2684293/Python3-oror-Recursive-oror-DFS-oror-Well-Explained-oror-Buttom-up-Approach-oror-2-LIne-solution
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if root: return 1+max(self.maxDepth(root.left),self.maxDepth(root.right)) return 0
maximum-depth-of-binary-tree
Python3 || Recursive || DFS || Well Explained || Buttom up Approach || 2 LIne solution
NitishKumarVerma
3
278
maximum depth of binary tree
104
0.732
Easy
636
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1765661/Python-3-greater-3-working-solutions-with-different-approaches
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 def helper(node, depth): if node: self.maxDepth = max(depth, self.maxDepth) helper(node.left, depth+1) helper(node.right, depth+1) self.maxDepth = 1 helper(root, 1) return self.maxDepth
maximum-depth-of-binary-tree
Python 3 -> 3 working solutions with different approaches
mybuddy29
3
106
maximum depth of binary tree
104
0.732
Easy
637
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1765661/Python-3-greater-3-working-solutions-with-different-approaches
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 def helper(node): if not node.left and not node.right: return 1 leftD, rightD = 0, 0 if node.left: leftD = helper(node.left) if node.right: rightD = helper(node.right) currDepth = max(leftD, rightD) + 1 self.maxDepth = max(self.maxDepth, currDepth) return currDepth self.maxDepth = 0 self.maxDepth = helper(root) return self.maxDepth
maximum-depth-of-binary-tree
Python 3 -> 3 working solutions with different approaches
mybuddy29
3
106
maximum depth of binary tree
104
0.732
Easy
638
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1397610/Python-Simple-recursive-solution
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 if root.left == None and root.right == None: return 1 return max(self.maxDepth(root.left) + 1, self.maxDepth(root.right) + 1)
maximum-depth-of-binary-tree
[Python] Simple recursive solution
yamshara
3
219
maximum depth of binary tree
104
0.732
Easy
639
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/642043/PythonJSGoC%2B%2B-by-O(n)-DFS-w-Comment
class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: # Base case: # Empty tree or empty leaf node return 0 else: # General case left = self.maxDepth( root.left ) right = self.maxDepth( root.right ) return max(left, right)+1
maximum-depth-of-binary-tree
Python/JS/Go/C++ by O(n) DFS [w/ Comment ]
brianchiang_tw
3
479
maximum depth of binary tree
104
0.732
Easy
640
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/642043/PythonJSGoC%2B%2B-by-O(n)-DFS-w-Comment
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: ## Base case on empty node or empty tree if not root: return 0 ## General cases return max( map(self.maxDepth, [root.left, root.right] ) ) + 1
maximum-depth-of-binary-tree
Python/JS/Go/C++ by O(n) DFS [w/ Comment ]
brianchiang_tw
3
479
maximum depth of binary tree
104
0.732
Easy
641
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/642043/PythonJSGoC%2B%2B-by-O(n)-DFS-w-Comment
class Solution: def maxDepth(self, root: TreeNode) -> int: self.tree_depth = 0 def helper( node: TreeNode, depth: int): if not node: # Base case # Empty node or empty tree return if not node.left and not node.right: # Base case # Update max depth when reach leaf node self.tree_depth = max( self.tree_depth, depth ) else: # General case # Keep DFS down to next level helper( node.left, depth + 1) helper( node.right, depth + 1) # ------------------------------------------------ helper( node = root, depth = 1 ) return self.tree_depth
maximum-depth-of-binary-tree
Python/JS/Go/C++ by O(n) DFS [w/ Comment ]
brianchiang_tw
3
479
maximum depth of binary tree
104
0.732
Easy
642
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2158641/Python-DFS-recursive-oror-BFS-oror-DFS-iterative-solution
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 res = 1 stack = [[root, 1]] while stack: node, depth = stack.pop() if node: res = max(res, depth) stack.append([node.left, depth+1]) stack.append([node.right, depth+1]) return res
maximum-depth-of-binary-tree
Python DFS recursive || BFS || DFS iterative solution
sagarhasan273
2
22
maximum depth of binary tree
104
0.732
Easy
643
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2158641/Python-DFS-recursive-oror-BFS-oror-DFS-iterative-solution
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 level = 0 q = deque([root]) while q: for i in range(len(q)): node = q.popleft() if node.left: q.append(node.left) if node.right: q.append(node.right) level += 1 return level
maximum-depth-of-binary-tree
Python DFS recursive || BFS || DFS iterative solution
sagarhasan273
2
22
maximum depth of binary tree
104
0.732
Easy
644
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/320215/Python-Iterative-solution-98-faster
class Solution: def maxDepth(self, root: TreeNode) -> int: queue = [] if root is not None: queue.append(root) depth = 0 while queue: depth += 1 temp = [] for node in queue: if node is not None: if node.left is not None: temp.append(node.left) if node.right is not None: temp.append(node.right) queue = temp return depth
maximum-depth-of-binary-tree
Python Iterative solution 98% faster
iseedeadpeople7272
2
130
maximum depth of binary tree
104
0.732
Easy
645
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2324078/Python-Intuitive-Recursive-and-Iterative-Solutions
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if root is None: return 0 left = self.maxDepth(root.left) right = self.maxDepth(root.right) if left >= right: return left + 1 else: return right + 1
maximum-depth-of-binary-tree
Python Intuitive Recursive and Iterative Solutions
PythonicLava
1
306
maximum depth of binary tree
104
0.732
Easy
646
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2324078/Python-Intuitive-Recursive-and-Iterative-Solutions
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if root is None: return 0 stack = [] stack.append((root, 1)) res = 0 while stack: node, depth = stack.pop() if node: res = max(res, depth) stack.append((node.left, depth+1)) stack.append((node.right, depth+1)) return res
maximum-depth-of-binary-tree
Python Intuitive Recursive and Iterative Solutions
PythonicLava
1
306
maximum depth of binary tree
104
0.732
Easy
647
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2246487/Python3-recursive-DFS
class Solution: def maxDepth(self, root: TreeNode) -> int: if root==None: return 0 left = self.maxDepth(root.left) right = self.maxDepth(root.right) return max(left,right)+1
maximum-depth-of-binary-tree
📌 Python3 recursive DFS
Dark_wolf_jss
1
8
maximum depth of binary tree
104
0.732
Easy
648
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2197384/Simple-Python-solution-with-recursion
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if root is None: return 0 else: left = self.maxDepth(root.left) right = self.maxDepth(root.right) if left > right: return left + 1 else: return right + 1
maximum-depth-of-binary-tree
Simple Python solution with recursion
lyubol
1
99
maximum depth of binary tree
104
0.732
Easy
649
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2157178/Faster-than-96.33-Python
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
maximum-depth-of-binary-tree
Faster than 96.33%-Python
jayeshvarma
1
69
maximum depth of binary tree
104
0.732
Easy
650
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1927814/Python-easy-recursive-solution
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
maximum-depth-of-binary-tree
Python easy recursive solution
alishak1999
1
104
maximum depth of binary tree
104
0.732
Easy
651
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1769375/Python-or-One-liner-or-O(N)
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: return 0 if not root else max(self.maxDepth(root.left),self.maxDepth(root.right))+1
maximum-depth-of-binary-tree
Python | One liner | O(N)
vishyarjun1991
1
190
maximum depth of binary tree
104
0.732
Easy
652
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1613239/Python-Recursion-Top-Down-and-Bottom-Up
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: self.res = 0 self.helper(root, 1) return self.res def helper(self, node, depth): if not node: return self.res = max(self.res, depth) self.helper(node.left, depth+1) self.helper(node.right, depth+1)
maximum-depth-of-binary-tree
Python Recursion Top Down & Bottom Up
aiqiaiqi
1
126
maximum depth of binary tree
104
0.732
Easy
653
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1613239/Python-Recursion-Top-Down-and-Bottom-Up
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: return self.helper(root) def helper(self, node): if not node: return 0 L = self.helper(node.left) R = self.helper(node.right) return max(L, R) +1
maximum-depth-of-binary-tree
Python Recursion Top Down & Bottom Up
aiqiaiqi
1
126
maximum depth of binary tree
104
0.732
Easy
654
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1527176/Simple-recursive-solution-(python)
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if root: return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) return 0
maximum-depth-of-binary-tree
Simple recursive solution (python)
dereky4
1
212
maximum depth of binary tree
104
0.732
Easy
655
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1176308/python-3-lines-faster-than-90%2B-easy-to-unsterstand
class Solution: def maxDepth(self, root: TreeNode) -> int: def dfs(node): return 0 if node is None else max(dfs(node.left), dfs(node.right)) + 1 return dfs(root)
maximum-depth-of-binary-tree
python 3 lines, faster than 90+, easy to unsterstand
dustlihy
1
267
maximum depth of binary tree
104
0.732
Easy
656
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1133749/Python3-solution-with-recursion
class Solution: depth: int def __init__(self): self.depth = 0 def maxDepth(self, root: TreeNode) -> int: if not root: return self.depth def checkDepth(node: TreeNode, cur_depth: int) -> None: if not node: return if not node.left and not node.right: self.depth = max(self.depth, cur_depth) checkDepth(node.left, cur_depth+1) checkDepth(node.right, cur_depth+1) check_depth(root, 1) return self.depth
maximum-depth-of-binary-tree
Python3 solution with recursion
alexforcode
1
75
maximum depth of binary tree
104
0.732
Easy
657
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1046771/Python3-easy-recursive-solution
class Solution: def __init__(self): self.count = 0 def maxDepth(self, root: TreeNode) -> int: if root == None: return 0 else: self.count = 1 + max(self.maxDepth(root.left),self.maxDepth(root.right)) return self.count
maximum-depth-of-binary-tree
Python3 easy recursive solution
EklavyaJoshi
1
93
maximum depth of binary tree
104
0.732
Easy
658
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/997407/python3-top-down-and-bottom-up-summary
class Solution: def maxDepth(self, root: TreeNode) -> int: self.res = 0 if not root: return self.res def helper(node: TreeNode, depth: int): if not node: # base case self.res = max(self.res, depth) else: helper(node.left, depth + 1) helper(node.right, depth + 1) helper(root, 0) return self.res
maximum-depth-of-binary-tree
python3 top-down & bottom-up summary
IvyFan
1
153
maximum depth of binary tree
104
0.732
Easy
659
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/997407/python3-top-down-and-bottom-up-summary
class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 # base case left_depth = self.maxDepth(root.left) right_depth = self.maxDepth(root.right) return max(left_depth, right_depth) + 1
maximum-depth-of-binary-tree
python3 top-down & bottom-up summary
IvyFan
1
153
maximum depth of binary tree
104
0.732
Easy
660
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/589325/Python-2-lines
class Solution: def maxDepth(self, root: TreeNode, cnt = 0) -> int: if not root: return cnt return max(self.maxDepth(root.left, cnt+1), self.maxDepth(root.right, cnt+1))
maximum-depth-of-binary-tree
Python - 2 lines
frankv55
1
74
maximum depth of binary tree
104
0.732
Easy
661
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/576806/Python-Iterative-99.52-speed-90.62-space
class Solution: def maxDepth(self, root: TreeNode) -> int: stack = [[root, 1]] level = 0 max_level = 0 while stack and root: root, level = stack.pop(0) if not root.left and not root.right: max_level = max(level, max_level) if root.left: stack.append([root.left, level+1]) if root.right: stack.append([root.right, level+1]) return max_level
maximum-depth-of-binary-tree
Python - Iterative - 99.52% speed, 90.62% space
frankv55
1
118
maximum depth of binary tree
104
0.732
Easy
662
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2833002/Python3-and-C-oror-Easy-oror-Faster-than-99
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: return self.traverse(root, 1) if root else 0 def traverse(self, node, depth): if node: return max(self.traverse(node.left, depth+1), self.traverse(node.right, depth+1)) else: return max(0, depth-1)
maximum-depth-of-binary-tree
Python3 and C# || Easy || Faster than 99%
TheSnappl
0
1
maximum depth of binary tree
104
0.732
Easy
663
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2815126/Python3-oror-2-Lines-of-code-oror-Easy-and-Fast
class Solution: def maxDepth(self, root: Optional[TreeNode], num = 0) -> int: if root == None: return num return max(self.maxDepth(root.right, num+1), self.maxDepth(root.left, num+1))
maximum-depth-of-binary-tree
✅ Python3 || 2 Lines of code || Easy and Fast
PabloVE2001
0
3
maximum depth of binary tree
104
0.732
Easy
664
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2815122/Python3-oror-Faster-than-94.22
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: return maxDepth(root, 0) def maxDepth(root, num): if root == None: return num return max(maxDepth(root.right, num+1), maxDepth(root.left, num+1))
maximum-depth-of-binary-tree
✅ Python3 || Faster than 94.22%
PabloVE2001
0
2
maximum depth of binary tree
104
0.732
Easy
665
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2802203/104.-Maximum-Depth-of-Binary-Tree-oror-Python3
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: return height(root) def height(root): if not root: return 0 lh=height(root.left) rh=height(root.right) return max(lh,rh)+1
maximum-depth-of-binary-tree
104. Maximum Depth of Binary Tree || Python3
shagun_pandey
0
2
maximum depth of binary tree
104
0.732
Easy
666
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2799940/Python3-One-liner-Recursive-DFS-Solution
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: return 0 if root == None else 1+ max(self.maxDepth(root.left),self.maxDepth(root.right))
maximum-depth-of-binary-tree
Python3 One-liner Recursive DFS Solution
neil_paul
0
4
maximum depth of binary tree
104
0.732
Easy
667
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2786978/Easy-and-Fast-Python-Solution-(2-lines-93)
class Solution: def maxDepth_1(self, root: Optional[TreeNode]) -> int: if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
maximum-depth-of-binary-tree
✅ Easy and Fast Python Solution (2-lines, 93%)
scissor
0
1
maximum depth of binary tree
104
0.732
Easy
668
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2781064/Python-3-or-Beats-93-speed!
class Solution: def maxDepth(self, root: Optional[TreeNode], current = 1) -> int: if root is None: return 0 if root.left is None and root.right is None: return current else: return max(self.maxDepth(root.left, current + 1), self.maxDepth(root.right, current + 1))
maximum-depth-of-binary-tree
Python 3 | Beats 93% speed!
niccolosottile
0
1
maximum depth of binary tree
104
0.732
Easy
669
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/2777963/I-hate-DFS-so-came-up-with-BFS-Python
class Solution: def maxDepth(self, root: Optional[TreeNode]): queue = [] height = 0 if not root: return 0 queue.append(root) while queue: current_length = len(queue) height += 1 for _ in range(0, current_length): popped_elem = queue.pop(0) if popped_elem.left: queue.append(popped_elem.left) if popped_elem.right: queue.append(popped_elem.right) return height
maximum-depth-of-binary-tree
I hate DFS so came up with BFS Python
xrssa
0
2
maximum depth of binary tree
104
0.732
Easy
670
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/689647/Python3-stack-O(N)
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: loc = {x : i for i, x in enumerate(inorder)} root = None stack = [] for x in preorder: if not root: root = node = TreeNode(x) elif loc[x] < loc[node.val]: stack.append(node) node.left = node = TreeNode(x) else: while stack and loc[stack[-1].val] < loc[x]: node = stack.pop() # backtracking node.right = node = TreeNode(x) return root
construct-binary-tree-from-preorder-and-inorder-traversal
[Python3] stack O(N)
ye15
7
371
construct binary tree from preorder and inorder traversal
105
0.609
Medium
671
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/689647/Python3-stack-O(N)
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: loc = {x: i for i, x in enumerate(inorder)} pre = iter(preorder) def fn(lo, hi): """Return node constructed from inorder[lo:hi].""" if lo == hi: return None k = loc[next(pre)] return TreeNode(inorder[k], fn(lo, k), fn(k+1, hi)) return fn(0, len(inorder))
construct-binary-tree-from-preorder-and-inorder-traversal
[Python3] stack O(N)
ye15
7
371
construct binary tree from preorder and inorder traversal
105
0.609
Medium
672
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/689647/Python3-stack-O(N)
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: loc = {x: i for i, x in enumerate(inorder)} k = 0 def fn(lo, hi): """Return BST constructed from inorder[lo:hi].""" nonlocal k if lo < hi: val = preorder[k] mid = loc[val] k += 1 return TreeNode(val, fn(lo, mid), fn(mid+1, hi)) return fn(0, len(inorder))
construct-binary-tree-from-preorder-and-inorder-traversal
[Python3] stack O(N)
ye15
7
371
construct binary tree from preorder and inorder traversal
105
0.609
Medium
673
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2098536/Python3-O(N)-Time-O(1)-Space-Recursive-Solution
class Solution: def buildTree(self, preorder, inorder): inorderIndexDict = {ch : i for i, ch in enumerate(inorder)} self.rootIndex = 0 def solve(l, r): if l > r: return None root = TreeNode(preorder[self.rootIndex]) self.rootIndex += 1 i = inorderIndexDict[root.val] root.left = solve(l, i-1) root.right = solve(i+1, r) return root return solve(0, len(inorder)-1) # Time: O(N) # Space: O(1)
construct-binary-tree-from-preorder-and-inorder-traversal
[Python3] O(N) Time, O(1) Space Recursive Solution
samirpaul1
4
206
construct binary tree from preorder and inorder traversal
105
0.609
Medium
674
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/1460628/Python-or-Readable-Solution-or-Recursion
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: if len(preorder) == 0: return None # This gives the root data rootData = preorder[0] root = TreeNode(rootData) rootIdx = -1 for i in range(len(inorder)): if rootData == inorder[i]: rootIdx = i break if rootIdx == -1: return None # This gives the leftInorder leftInorder = inorder[:rootIdx] #This gives the rightInorder rightInorder = inorder[rootIdx+1:] lenLeftSubTree = len(leftInorder) leftPreorder = preorder[1:lenLeftSubTree+1] rightPreorder = preorder[lenLeftSubTree+1:] # Recursion will build the tree leftChild = self.buildTree(leftPreorder, leftInorder) rightChild = self.buildTree(rightPreorder, rightInorder) # Making connnections of the tree root.left = leftChild root.right = rightChild return root
construct-binary-tree-from-preorder-and-inorder-traversal
Python | Readable Solution | Recursion
dkamat01
2
312
construct binary tree from preorder and inorder traversal
105
0.609
Medium
675
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2812289/Recursive-partitioning-of-in-order-traversal
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: def makeNode(p, i, j): if j-i < 1: return None p[0] += 1 return TreeNode(inorder[i]) if j-i == 1 else makeTree(p,i,j) def makeTree(p,i,j): v = preorder[p[0]] k = inorder.index(v, i, j) return TreeNode(v, makeNode(p, i, k), makeNode(p, k + 1, j)) return makeTree([0],0,len(inorder))
construct-binary-tree-from-preorder-and-inorder-traversal
Recursive partitioning of in-order traversal
constantstranger
1
72
construct binary tree from preorder and inorder traversal
105
0.609
Medium
676
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2812289/Recursive-partitioning-of-in-order-traversal
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: idx = {v:i for i, v in enumerate(inorder)} def makeNode(p, i, j): if j-i < 1: return None p[0] += 1 return TreeNode(inorder[i]) if j-i == 1 else makeTree(p,i,j) def makeTree(p,i,j): v = preorder[p[0]] return TreeNode(v, makeNode(p, i, idx[v]), makeNode(p, idx[v] + 1, j)) return makeTree([0],0,len(inorder))
construct-binary-tree-from-preorder-and-inorder-traversal
Recursive partitioning of in-order traversal
constantstranger
1
72
construct binary tree from preorder and inorder traversal
105
0.609
Medium
677
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2282568/Python-Recursive-Solution
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: if len(preorder) == 0 or len(inorder) == 0: return None root_val = preorder.pop(0) root_index = inorder.index(root_val) root = TreeNode(root_val) root.left = self.buildTree(preorder, inorder[:root_index]) root.right = self.buildTree(preorder, inorder[root_index+1:]) return root
construct-binary-tree-from-preorder-and-inorder-traversal
Python Recursive Solution
PythonicLava
1
96
construct binary tree from preorder and inorder traversal
105
0.609
Medium
678
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2281045/Python-3-oror-DFS-Binary-Tree
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: def dfs(preorder, inorder): if preorder and inorder: node = TreeNode(preorder[0]) i = inorder.index(preorder[0]) node.left = dfs(preorder[1:i+1], inorder[:i]) node.right = dfs(preorder[i+1:], inorder[i+1:]) return node return None return dfs(preorder, inorder)
construct-binary-tree-from-preorder-and-inorder-traversal
Python 3 || DFS Binary Tree
sagarhasan273
1
38
construct binary tree from preorder and inorder traversal
105
0.609
Medium
679
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2279453/Python3-DFS
class Solution: def get_result(self,preorder,inorder): if len(inorder)==0 or len(preorder)==0: return None root = TreeNode(preorder[0]) index = inorder.index(preorder[0]) del preorder[0] root.left = self.get_result(preorder,inorder[:index]) root.right = self.get_result(preorder,inorder[index+1:]) return root def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: return self.get_result(preorder,inorder)
construct-binary-tree-from-preorder-and-inorder-traversal
📌 Python3 DFS
Dark_wolf_jss
1
8
construct binary tree from preorder and inorder traversal
105
0.609
Medium
680
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2279247/python3-or-easy-or-explained-or-easy-to-understand
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: if inorder: # getting the index of root element for current subtree index = inorder.index(preorder.pop(0)) # initialises root element root = TreeNode(inorder[index]) # using recursion to find the next element with remaining sets of elements # elements in inorder[:index] will always be the left subtree of inorder[index] root.left = self.buildTree(preorder, inorder[:index]) # elements in inorder[index+1:] will always be the right subtree of inorder[index] root.right = self.buildTree(preorder, inorder[index+1:]) return root
construct-binary-tree-from-preorder-and-inorder-traversal
python3 | easy | explained | easy to understand
H-R-S
1
88
construct binary tree from preorder and inorder traversal
105
0.609
Medium
681
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2242519/Python3-Solving-3-binary-tree-construction-problems-using-same-template
class Solution: def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]: if not preorder or not postorder: return root = TreeNode(preorder[0]) if len(preorder) == 1: return root index = postorder.index(preorder[1]) root.left = self.constructFromPrePost(preorder[1:index+2], postorder[:index+1]) root.right = self.constructFromPrePost(preorder[index+2:], postorder[index+1:-1]) return root
construct-binary-tree-from-preorder-and-inorder-traversal
[Python3] Solving 3 binary tree construction problems using same template
Gp05
1
57
construct binary tree from preorder and inorder traversal
105
0.609
Medium
682
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2242519/Python3-Solving-3-binary-tree-construction-problems-using-same-template
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: if not preorder or not inorder: return root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1: mid+1], inorder[:mid]) root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:]) return root
construct-binary-tree-from-preorder-and-inorder-traversal
[Python3] Solving 3 binary tree construction problems using same template
Gp05
1
57
construct binary tree from preorder and inorder traversal
105
0.609
Medium
683
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2242519/Python3-Solving-3-binary-tree-construction-problems-using-same-template
class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: if not postorder or not inorder: return root = TreeNode(postorder[-1]) mid = inorder.index(postorder[-1]) root.left = self.buildTree(inorder[:mid], postorder[:mid]) root.right = self.buildTree(inorder[mid+1:], postorder[mid:-1]) return root
construct-binary-tree-from-preorder-and-inorder-traversal
[Python3] Solving 3 binary tree construction problems using same template
Gp05
1
57
construct binary tree from preorder and inorder traversal
105
0.609
Medium
684
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/1742500/Python-using-dict-for-O(1)-lookup.-Time%3A-O(N)-Space%3A-O(N)
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: def build(p_s, p_e, i_s, i_e): if p_s >= p_e: return None node = TreeNode(preorder[p_s]) idx = idxs[preorder[p_s]] node.left = build(p_s + 1, p_s + idx - i_s + 1, i_s, idx) node.right = build(p_s + idx - i_s + 1, p_e, idx + 1, i_e) return node idxs = {n: i for i, n in enumerate(inorder)} return build(0, len(preorder), 0, len(inorder))
construct-binary-tree-from-preorder-and-inorder-traversal
Python, using dict for O(1) lookup. Time: O(N), Space: O(N)
blue_sky5
1
80
construct binary tree from preorder and inorder traversal
105
0.609
Medium
685
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/1418035/Easier-than-given-solution-w-python-and-comments
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: def recur(preorder, inorder): if not inorder: return None #notice that this recursive function follows the same recursive format as a preorder traversal. #we pop the root node from preorder, then we build left subtree, then right subtree. So continuously #popping from preorder should do and give us the root value of the entire tree/subtree represented. root = TreeNode(preorder.pop(0)) root_idx = inorder.index(root.val) #the left subtree will be located to the left of the root value in inorder root.left = recur(preorder, inorder[:root_idx]) #the right subtree will be located to the right of the root value in inorder root.right = recur(preorder, inorder[root_idx+1:]) return root return recur(preorder, inorder)
construct-binary-tree-from-preorder-and-inorder-traversal
Easier than given solution w/ python and comments
mguthrie45
1
190
construct binary tree from preorder and inorder traversal
105
0.609
Medium
686
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/1261560/Python3-simple-solution-using-recursion
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def build(a, b, c, preorder, inorder): if b > c or a > len(preorder)-1: return root = TreeNode(preorder[a]) x = inorder.index(preorder[a], b, c+1) root.left = build(a+1, b, x-1, preorder, inorder) root.right = build(a+x-b+1, x+1, c, preorder, inorder) return root return build(0, 0, len(inorder)-1, preorder, inorder)
construct-binary-tree-from-preorder-and-inorder-traversal
Python3 simple solution using recursion
EklavyaJoshi
1
68
construct binary tree from preorder and inorder traversal
105
0.609
Medium
687
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/695881/Short-simple-recursive-solution
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: root = None if preorder: root = TreeNode(preorder.pop(0)) index = inorder.index(root.val) root.left = self.buildTree(preorder, inorder[:index]) root.right = self.buildTree(preorder, inorder[index+1:]) return(root)
construct-binary-tree-from-preorder-and-inorder-traversal
Short, simple recursive solution
AdityaCh
1
255
construct binary tree from preorder and inorder traversal
105
0.609
Medium
688
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2843307/Python-Recursion-without-a-hash-map
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: pre_index, in_index = 0, 0 len_tree = len(preorder) def pre_in(right_anc): # build the tree which has the nearest right ancester right_anc nonlocal preorder, inorder, pre_index, in_index, len_tree # if the next inorder value is the right ancester, that means the subtree construction is done if pre_index == len_tree or inorder[in_index] == right_anc: return None # consume a value in preorder as the root root = TreeNode(preorder[pre_index]) pre_index += 1 # the left tree is the next tree with the right ancester as this node. root.left = pre_in(root.val) in_index += 1 # the right tree is the next tree with the right ancester as the right ancester of this node root.right = pre_in(right_anc) return root return pre_in(None)
construct-binary-tree-from-preorder-and-inorder-traversal
[Python] Recursion without a hash map
i-hate-covid
0
2
construct binary tree from preorder and inorder traversal
105
0.609
Medium
689
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2728282/Construct-Binary-Tree-from-PreorderPostorder-and-Inorder
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: inMap = {} for i in range(len(inorder)): inMap[inorder[i]] = i return self.solve(preorder, 0, len(preorder)-1, inorder, 0, len(inorder)-1, inMap) def solve(self, preorder, prestart, preend, inorder, instart, inend, inMap): if prestart > preend or instart > inend: return None root = TreeNode(preorder[prestart]) inroot = inMap[root.val] numsleft = inroot - instart root.left = self.solve(preorder, prestart + 1, prestart + numsleft, inorder, instart, inroot-1, inMap) root.right = self.solve(preorder, prestart+numsleft + 1, preend, inorder, inroot+1, inend, inMap) return root
construct-binary-tree-from-preorder-and-inorder-traversal
Construct Binary Tree from Preorder/Postorder and Inorder
hacktheirlives
0
4
construct binary tree from preorder and inorder traversal
105
0.609
Medium
690
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2728282/Construct-Binary-Tree-from-PreorderPostorder-and-Inorder
class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: if len(inorder) != len(postorder): return None mp = {} for i in range(len(inorder)): mp[inorder[i]] = i return self.solve(inorder, 0, len(inorder)-1, postorder, 0, len(postorder)-1, mp) def solve(self, inorder, iS, iE, postorder, pS, pE, mp): if iS > iE or pS > pE: return None root = TreeNode(postorder[pE]) inroot = mp[postorder[pE]] numsleft = inroot - iS root.left = self.solve(inorder, iS, inroot-1, postorder, pS, pS+numsleft-1, mp) root.right = self.solve(inorder, inroot+1, iE, postorder, pS+numsleft, pE-1, mp) return root
construct-binary-tree-from-preorder-and-inorder-traversal
Construct Binary Tree from Preorder/Postorder and Inorder
hacktheirlives
0
4
construct binary tree from preorder and inorder traversal
105
0.609
Medium
691
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2523241/Python-DFS-Solution
class Solution: # Time: O(n*n) &amp; Space: O(n*n) def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: if not preorder or not inorder: return None root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1:mid+1], inorder[:mid]) root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:]) return root
construct-binary-tree-from-preorder-and-inorder-traversal
Python DFS Solution
DanishKhanbx
0
66
construct binary tree from preorder and inorder traversal
105
0.609
Medium
692
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2522002/Python-shortest-recursive-Solution-or-with-explanation
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: #doesnt matter which one we check, as we are doing slicing on both the lists if not preorder or not inorder: return # root will be the first node in the preorder list - 0th position root = TreeNode(preorder[0]) # finding the position of the root in inorder, as the elements to its left will be the left subtree and elements to the right will be the right sub tree mid = inorder.index(preorder[0]) # recursive call. left tree will be from 1st position till mid +1 ( number of elements to the left of root in inorder list) root.left = self.buildTree(preorder[1:mid+1], inorder[:mid]) # recursive call. right tree will be from mid + 1 till end ( number of elements to the right of root in inorder list) root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:]) #returning original root return root ```
construct-binary-tree-from-preorder-and-inorder-traversal
Python shortest recursive Solution | with explanation
neeraj02
0
21
construct binary tree from preorder and inorder traversal
105
0.609
Medium
693
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2314341/Python-Time%3A-288-ms-oror-Mem%3A-88.9MB-oror-Easy-Understand-oror-Recursive
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: if not preorder or not inorder: return None root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1:mid+1], inorder[:mid+1]) root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:]) return root
construct-binary-tree-from-preorder-and-inorder-traversal
[Python] Time: 288 ms || Mem: 88.9MB || Easy Understand || Recursive
Buntynara
0
38
construct binary tree from preorder and inorder traversal
105
0.609
Medium
694
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2309693/Python3-oror-Recursion-solution
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: if not inorder or not preorder: return None x=inorder.index(preorder[0]) head=TreeNode(preorder[0]) head.left=self.buildTree(preorder[1:x+1],inorder[:x]) head.right=self.buildTree(preorder[x+1:],inorder[x+1:]) return head
construct-binary-tree-from-preorder-and-inorder-traversal
Python3 || Recursion solution
udaymewada
0
23
construct binary tree from preorder and inorder traversal
105
0.609
Medium
695
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2282772/Python-solution-or-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: if not preorder or not inorder: return None root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1:mid + 1], inorder[:mid]) root.right = self.buildTree(preorder[mid + 1:], inorder[mid + 1:]) return root
construct-binary-tree-from-preorder-and-inorder-traversal
Python solution | Construct Binary Tree from Preorder and Inorder Traversal
nishanrahman1994
0
23
construct binary tree from preorder and inorder traversal
105
0.609
Medium
696
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2281694/python3-simple-recursive
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: self.count = 0 def dfs(values): if not values: return None node = TreeNode(preorder[self.count]) self.count += 1 index = values.index(node.val) node.left = dfs(values[:index]) node.right = dfs(values[index+1:]) return node return dfs(inorder)
construct-binary-tree-from-preorder-and-inorder-traversal
python3, simple recursive
pjy953
0
5
construct binary tree from preorder and inorder traversal
105
0.609
Medium
697
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2281570/100-Java-and-Python-Optimal-Solution
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def array_to_tree(left, right): nonlocal preorder_index # if there are no elements to construct the tree if left > right: return None # select the preorder_index element as the root and increment it root_value = preorder[preorder_index] root = TreeNode(root_value) preorder_index += 1 # build left and right subtree # excluding inorder_index_map[root_value] element because it's the root root.left = array_to_tree(left, inorder_index_map[root_value] - 1) root.right = array_to_tree(inorder_index_map[root_value] + 1, right) return root preorder_index = 0 # build a hashmap to store value -> its index relations inorder_index_map = {} for index, value in enumerate(inorder): inorder_index_map[value] = index return array_to_tree(0, len(preorder) - 1)
construct-binary-tree-from-preorder-and-inorder-traversal
✔️ 100% - Java and Python Optimal Solution
Theashishgavade
0
53
construct binary tree from preorder and inorder traversal
105
0.609
Medium
698
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/2280170/Python3-Solution-with-using-hashmap
class Solution: def __init__(self): self.root_idx = 0 def tree_builder(self, preorder, left_idx, right_idx, val2idx): if left_idx > right_idx: return None root_val = preorder[self.root_idx] self.root_idx += 1 root = TreeNode( root_val, self.tree_builder(preorder, left_idx, val2idx[root_val] - 1, val2idx), self.tree_builder(preorder, val2idx[root_val] + 1, right_idx, val2idx) ) return root def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: val2idx = {} for idx in range(len(inorder)): val2idx[inorder[idx]] = idx return self.tree_builder(preorder, 0, len(preorder) - 1, val2idx)
construct-binary-tree-from-preorder-and-inorder-traversal
[Python3] Solution with using hashmap
maosipov11
0
7
construct binary tree from preorder and inorder traversal
105
0.609
Medium
699