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/balanced-binary-tree/discuss/2490619/Python-Solution-using-recursion | class Solution:
def getHeight(self,root,h):
if root is None:
return h
return max(self.getHeight(root.left,h+1),self.getHeight(root.right,h+1))
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if root is None:
return True
if root:
ht_right=self.getHeight(root.right,1)
ht_left=self.getHeight(root.left,1)
if abs(ht_left-ht_right)>1:
return False
rt = self.isBalanced(root.left)
lt = self.isBalanced(root.right)
if not rt or not lt:
return False
return True | balanced-binary-tree | Python Solution [using recursion] | miyachan | 0 | 48 | balanced binary tree | 110 | 0.483 | Easy | 800 |
https://leetcode.com/problems/balanced-binary-tree/discuss/2409309/Simple-recursive-solution-or-Python-or-O(n)-or-DFS | class Solution:
def isHeightBalanced(self, root):
if root:
left_height, left_balanced = self.isHeightBalanced(root.left)
right_height, right_balanced = self.isHeightBalanced(root.right)
return (
max(left_height, right_height) + 1,
(
left_balanced
and right_balanced
and (abs(right_height - left_height) <= 1)
),
)
return (0, True)
def isBalanced(self, root: Optional[TreeNode]) -> bool:
_, is_balanced = self.isHeightBalanced(root)
return is_balanced | balanced-binary-tree | Simple recursive solution | Python | O(n) | DFS | wilspi | 0 | 156 | balanced binary tree | 110 | 0.483 | Easy | 801 |
https://leetcode.com/problems/balanced-binary-tree/discuss/2407627/SIMPLE-96.45-Faster-Python-recursive | class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
heightDict = {}
if not root:
return True
def checkBalance(root: TreeNode) -> bool:
leftHeight = 0
rightHeight = 0
if root.left:
rootLeftCheck = checkBalance(root.left)
if not rootLeftCheck:
return False
leftHeight = heightDict[root.left]
if root.right:
rootRightCheck = checkBalance(root.right)
if not rootRightCheck:
return False
rightHeight = heightDict[root.right]
if rightHeight - leftHeight > 1 or leftHeight - rightHeight > 1:
return False
else:
# add current height into dict:
rootHeight = max(leftHeight, rightHeight) + 1
heightDict[root] = rootHeight
return True
return checkBalance(root) | balanced-binary-tree | SIMPLE 96.45% Faster, Python - recursive | anhduong275 | 0 | 117 | balanced binary tree | 110 | 0.483 | Easy | 802 |
https://leetcode.com/problems/balanced-binary-tree/discuss/2041544/Python-runtime-60.80-memory-29.46 | class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
def recur(node, level):
if not node:
return level-1
left = recur(node.left, level+1)
right = recur(node.right, level+1)
if not left or not right:
return 0
if abs(left-right) > 1:
return 0
return max(left, right)
level = recur(root, 1)
if not level:
return False
return True | balanced-binary-tree | Python, runtime 60.80%, memory 29.46% | tsai00150 | 0 | 167 | balanced binary tree | 110 | 0.483 | Easy | 803 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2429057/Very-Easy-oror-100-oror-Fully-Explained-(C%2B%2B-Java-Python-JS-C-Python3) | class Solution(object):
def minDepth(self, root):
# Base case...
# If the subtree is empty i.e. root is NULL, return depth as 0...
if root is None: return 0
# Initialize the depth of two subtrees...
leftDepth = self.minDepth(root.left)
rightDepth = self.minDepth(root.right)
# If the both subtrees are empty...
if root.left is None and root.right is None:
return 1
# If the left subtree is empty, return the depth of right subtree after adding 1 to it...
if root.left is None:
return 1 + rightDepth
# If the right subtree is empty, return the depth of left subtree after adding 1 to it...
if root.right is None:
return 1 + leftDepth
# When the two child function return its depth...
# Pick the minimum out of these two subtrees and return this value after adding 1 to it...
return min(leftDepth, rightDepth) + 1; # Adding 1 is the current node which is the parent of the two subtrees... | minimum-depth-of-binary-tree | Very Easy || 100% || Fully Explained (C++, Java, Python, JS, C, Python3) | PratikSen07 | 32 | 2,200 | minimum depth of binary tree | 111 | 0.437 | Easy | 804 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2429057/Very-Easy-oror-100-oror-Fully-Explained-(C%2B%2B-Java-Python-JS-C-Python3) | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
# Base case...
# If the subtree is empty i.e. root is NULL, return depth as 0...
if root is None: return 0
# Initialize the depth of two subtrees...
leftDepth = self.minDepth(root.left)
rightDepth = self.minDepth(root.right)
# If the both subtrees are empty...
if root.left is None and root.right is None:
return 1
# If the left subtree is empty, return the depth of right subtree after adding 1 to it...
if root.left is None:
return 1 + rightDepth
# If the right subtree is empty, return the depth of left subtree after adding 1 to it...
if root.right is None:
return 1 + leftDepth
# When the two child function return its depth...
# Pick the minimum out of these two subtrees and return this value after adding 1 to it...
return min(leftDepth, rightDepth) + 1; # Adding 1 is the current node which is the parent of the two subtrees... | minimum-depth-of-binary-tree | Very Easy || 100% || Fully Explained (C++, Java, Python, JS, C, Python3) | PratikSen07 | 32 | 2,200 | minimum depth of binary tree | 111 | 0.437 | Easy | 805 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/629657/Python-O(n)-by-DFS-and-BFS-85%2B-w-Comment | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
# base case for empty node or empty tree
return 0
if not root.left and not root.right:
# leaf node
return 1
elif not root.right:
# only has left sub-tree
return self.minDepth(root.left) + 1
elif not root.left:
# only has right sub-tree
return self.minDepth(root.right) + 1
else:
# has left sub-tree and right sub-tree
return min( map(self.minDepth, (root.left, root.right) ) ) + 1 | minimum-depth-of-binary-tree | Python O(n) by DFS and BFS 85%+ [w/ Comment] | brianchiang_tw | 16 | 2,200 | minimum depth of binary tree | 111 | 0.437 | Easy | 806 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/1467207/Python3-oror-Recursive-oror-Self-Understandable-oror-Easy-Understanding | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
def recurse(root):
if root.left is None and root.right is None:
return 1
if root.left is None and root.right:
return 1+recurse(root.right)
if root.left and root.right is None:
return 1+recurse(root.left)
if root.left and root.right:
return min(1+recurse(root.right),1+recurse(root.left))
return recurse(root) if root else 0 | minimum-depth-of-binary-tree | Python3 || Recursive || Self-Understandable || Easy-Understanding | bug_buster | 14 | 684 | minimum depth of binary tree | 111 | 0.437 | Easy | 807 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/1147375/Python-Easy-to-understand-DFS-logic-with-Comments | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0 # return 0 as depth if empty tree
elif not root.left and not root.right:
return 1 # base case handling
elif not root.left:
return self.minDepth(root.right)+1 # if no left child then only path is right, so consider right depth
elif not root.right:
return self.minDepth(root.left)+1 # if no right child then only path is left, so consider left depth
else:
return min(self.minDepth(root.left), self.minDepth(root.right))+1 # if both child exist then pick the minimum one, add one for current node and return min depth | minimum-depth-of-binary-tree | Python Easy to understand DFS logic with Comments | shootingstaradil | 8 | 479 | minimum depth of binary tree | 111 | 0.437 | Easy | 808 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/485658/Python-3-(seven-lines)-(beats-~95)-(BFS) | class Solution:
def minDepth(self, R: TreeNode) -> int:
if not R: return 0
N, A, d = [R], [], 1
while 1:
for n in N:
if n.left is n.right: return d
n.left and A.append(n.left), n.right and A.append(n.right)
N, A, d = A, [], d + 1
- Junaid Mansuri
- Chicago, IL | minimum-depth-of-binary-tree | Python 3 (seven lines) (beats ~95%) (BFS) | junaidmansuri | 3 | 783 | minimum depth of binary tree | 111 | 0.437 | Easy | 809 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2632384/Python-Elegant-and-Short-or-DFS | class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def minDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
left_depth = self.minDepth(root.left)
right_depth = self.minDepth(root.right)
return 1 + (
min(left_depth, right_depth) or
max(left_depth, right_depth)
) | minimum-depth-of-binary-tree | Python Elegant & Short | DFS | Kyrylo-Ktl | 2 | 242 | minimum depth of binary tree | 111 | 0.437 | Easy | 810 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2600509/Easy-recursive-Python-solution | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
if not root.left and not root.right: return 1
left=self.minDepth(root.left) if root.left else float('inf')
right=self.minDepth(root.right) if root.right else float('inf')
return 1+ min(left,right) | minimum-depth-of-binary-tree | Easy recursive Python π solution | InjySarhan | 2 | 248 | minimum depth of binary tree | 111 | 0.437 | Easy | 811 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/1768389/Python-Easiest-Approach | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
elif root.left is None and root.right is None:
return 1
elif root.left is None:
return self.minDepth(root.right)+1
elif root.right is None:
return self.minDepth(root.left)+1
else:
return min(self.minDepth(root.left),self.minDepth(root.right))+1 | minimum-depth-of-binary-tree | Python Easiest Approach | karansinghsnp | 2 | 168 | minimum depth of binary tree | 111 | 0.437 | Easy | 812 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/1234702/Python-Easiest-to-read-BFS | class Solution:
def minDepth(self, root: TreeNode) -> int:
# Readable BFS
# T: O(N)
# S: O(N)
if not root:
return 0
if not root.left and not root.right:
return 1
queue = [root]
depth = 1
while queue:
for _ in range(len(queue)):
node = queue.pop(0)
if not node.left and not node.right:
return depth
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
depth += 1
return depth | minimum-depth-of-binary-tree | Python Easiest to read BFS | treksis | 2 | 218 | minimum depth of binary tree | 111 | 0.437 | Easy | 813 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/905936/Python-BFS-and-DFS-Explained-(video-%2B-code) | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
q = collections.deque()
q.append((root, 1))
while q:
node, depth = q.popleft()
if not node.left and not node.right:
return depth
if node.left:
q.append((node.left, depth + 1))
if node.right:
q.append((node.right, depth + 1)) | minimum-depth-of-binary-tree | Python BFS and DFS Explained (video + code) | spec_he123 | 2 | 167 | minimum depth of binary tree | 111 | 0.437 | Easy | 814 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/905936/Python-BFS-and-DFS-Explained-(video-%2B-code) | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
if not root.right and root.left:
return 1 + self.minDepth(root.left)
if not root.left and root.right:
return 1 + self.minDepth(root.right)
return 1 + min(self.minDepth(root.left), self.minDepth(root.right)) | minimum-depth-of-binary-tree | Python BFS and DFS Explained (video + code) | spec_he123 | 2 | 167 | minimum depth of binary tree | 111 | 0.437 | Easy | 815 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2336115/Python3-or-O-(n)-space-or-O-(n)-time-or-BFS-or-Optimal-Solution | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
queue = deque([root])
currentLevel = 1
while queue:
currentLevelSize = len(queue)
for _ in range(currentLevelSize):
currentNode = queue.popleft()
if currentNode.left is None and currentNode.right is None:
return currentLevel
if currentNode.left:
queue.append(currentNode.left)
if currentNode.right:
queue.append(currentNode.right)
currentLevel += 1 | minimum-depth-of-binary-tree | Python3 | O (n) space | O (n) time | BFS | Optimal Solution | blessinto | 1 | 122 | minimum depth of binary tree | 111 | 0.437 | Easy | 816 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2323497/Python-recursive-code-intuitive-solution-with-explanation | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
# just a slight modification , in case both left andd right exist, we simply find min
# if only left exist , we find left
# if only right exist, we find right
if root is None:
return 0
left=self.minDepth(root.left)
right=self.minDepth(root.right)
if left and right:
return 1+min(left,right)
elif left:
return 1+left
return 1+right | minimum-depth-of-binary-tree | Python recursive code, intuitive solution with explanation | Aniket_liar07 | 1 | 139 | minimum depth of binary tree | 111 | 0.437 | Easy | 817 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2144542/Plain-Simple-BFS-Python-or-92 | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
q = [root]
depth = 0
while len(q) !=0:
q_len = len(q)
depth+=1
for _ in range(q_len):
curr = q.pop(0)
if curr is not None:
if curr.left:
q.append(curr.left)
if curr.right:
q.append(curr.right)
if not curr.left and not curr.right:
return depth
return depth | minimum-depth-of-binary-tree | Plain Simple BFS Python | 92% | bliqlegend | 1 | 87 | minimum depth of binary tree | 111 | 0.437 | Easy | 818 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/1544403/Python3-BFS-beats-99.1Runtime-and-85.87Memory | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root == None:
return 0
queue = [root]
depth = 0
while queue:
depth = depth + 1
for i in range(len(queue)):
node=queue.pop(0)
if node.left == None and node.right == None:
return depth
elif node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return -1
``` | minimum-depth-of-binary-tree | Python3 BFS beats 99.1%Runtime and 85.87%Memory | 17pchaloori | 1 | 226 | minimum depth of binary tree | 111 | 0.437 | Easy | 819 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/1207164/PythonPython3-Minimum-Depth-of-Binary-Tree | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: return 0
if (not root.left) and (not root.right):
return 1
h = 1
minimum = float('inf')
def calc_minDepth(node, h, minimum):
if h > minimum:
return minimum
if not node:
return float('inf')
if (not node.left) and (not node.right):
minimum = min(minimum, h)
return minimum
return min(calc_minDepth(node.left, 1 + h, minimum), calc_minDepth(node.right, 1 + h, minimum))
return calc_minDepth(root, h, minimum) | minimum-depth-of-binary-tree | [Python/Python3] Minimum Depth of Binary Tree | newborncoder | 1 | 691 | minimum depth of binary tree | 111 | 0.437 | Easy | 820 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/1156099/Python-Iterative-DFS-with-Optimization | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
stack = [(root, 1)]
minDepth = float('inf')
while stack:
node, depth = stack.pop()
if depth >= minDepth:
continue
if not node.left and not node.right:
minDepth = min(minDepth, depth)
else:
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
return minDepth | minimum-depth-of-binary-tree | Python Iterative DFS with Optimization | genefever | 1 | 113 | minimum depth of binary tree | 111 | 0.437 | Easy | 821 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/692332/Python3-concise-solutions | class Solution:
def minDepth(self, root: TreeNode) -> int:
def fn(node):
"""Return minimum depth of given node"""
if not node: return 0
if not node.left or not node.right: return 1 + fn(node.left) + fn(node.right)
return 1 + min(fn(node.left), fn(node.right))
return fn(root) | minimum-depth-of-binary-tree | [Python3] concise solutions | ye15 | 1 | 61 | minimum depth of binary tree | 111 | 0.437 | Easy | 822 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/692332/Python3-concise-solutions | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: return 0
ans = self.minDepth(root.left), self.minDepth(root.right)
return 1 + (min(ans) or max(ans)) | minimum-depth-of-binary-tree | [Python3] concise solutions | ye15 | 1 | 61 | minimum depth of binary tree | 111 | 0.437 | Easy | 823 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/692332/Python3-concise-solutions | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: return 0 #edge case
queue = [(root, 1)]
for node, i in queue:
if not node.left and not node.right: return i
if node.left: queue.append((node.left, i+1))
if node.right: queue.append((node.right, i+1)) | minimum-depth-of-binary-tree | [Python3] concise solutions | ye15 | 1 | 61 | minimum depth of binary tree | 111 | 0.437 | Easy | 824 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/692332/Python3-concise-solutions | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: return 0 # edge case
ans, queue = 1, [root]
while queue: # bfs by level
newq = []
for n in queue:
if n.left is n.right is None: return ans
if n.left: newq.append(n.left)
if n.right: newq.append(n.right)
ans, queue = ans+1, newq
return ans | minimum-depth-of-binary-tree | [Python3] concise solutions | ye15 | 1 | 61 | minimum depth of binary tree | 111 | 0.437 | Easy | 825 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/313197/Python3-dfs | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:return 0
self.depth = float('Inf')
def dfs(node, level):
if not node:return
if not node.right and not node.left:self.depth = min(self.depth, level)
if node.right:
dfs(node.right, level+1)
if node.left:
dfs(node.left, level+1)
dfs(root, 1)
return (self.depth) | minimum-depth-of-binary-tree | Python3 dfs | aj_to_rescue | 1 | 175 | minimum depth of binary tree | 111 | 0.437 | Easy | 826 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/254186/Python-Easy-to-Understand | class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
left = self.minDepth(root.left)
right = self.minDepth(root.right)
return left + right + 1 if (left == 0 or right == 0) else min(left, right) + 1 | minimum-depth-of-binary-tree | Python Easy to Understand | ccparamecium | 1 | 335 | minimum depth of binary tree | 111 | 0.437 | Easy | 827 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2831558/Python-super-simple-recursion-with-explanation | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
# root is a child of a leaf
if not root:
return 0
# root is not a leaf but has a branch missing
# so mindepth is depth of non-missing branch instead of min(0, depth)
if not root.left:
return 1 + self.minDepth(root.right)
if not root.right:
return 1 + self.minDepth(root.left)
# root is not a leaf
return 1 + min(self.minDepth(root.left), self.minDepth(root.right)) | minimum-depth-of-binary-tree | Python super simple recursion with explanation | AlecLeetcode | 0 | 1 | minimum depth of binary tree | 111 | 0.437 | Easy | 828 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2827660/simple-python-oror-bfs | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
# if tree empty
if not root:
return 0
# queue of tuples: (node, curr depth)
q = deque([(root, 0)])
# while q not empty
while(q):
# get front of queue
cur, lvl = q.popleft()
# if neither child exists, leaf node found
if not cur.left and not cur.right:
return (lvl + 1)
# if left child exists
if cur.left:
# enqueue it
q.append((cur.left, (lvl + 1)))
# if right child exists
if cur.right:
# enqueue it
q.append((cur.right, (lvl + 1))) | minimum-depth-of-binary-tree | simple python || bfs | wduf | 0 | 4 | minimum depth of binary tree | 111 | 0.437 | Easy | 829 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2811203/Intuitive-%2B-Recursive-Python-Solution | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
def bfs(root,count):
if root.left and root.right:
return min(bfs(root.left,count+1),bfs(root.right,count+1))
elif root.left and not root.right:
return bfs(root.left,count+1)
elif root.right and not root.left:
return bfs(root.right,count+1)
else:
return count
return bfs(root,1) | minimum-depth-of-binary-tree | Intuitive + Recursive Python Solution | khoai345678 | 0 | 3 | minimum depth of binary tree | 111 | 0.437 | Easy | 830 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2781058/Python-oror-O(N)-greaterTC-oror-O(logN)-greaterSC | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
res = 10**6
def dfs(root, d1):
nonlocal res
if not root:
return 10**6
if not root.left and not root.right:
res = min(res, d1)
return res
dfs(root.left, d1+1)
dfs(root.right, d1+1)
return res
return dfs(root, 1) if root else 0 | minimum-depth-of-binary-tree | Python || O(N)->TC || O(logN)->SC | ak_guy | 0 | 5 | minimum depth of binary tree | 111 | 0.437 | Easy | 831 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2766622/Python-99-Faster-Solution | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
queue = [root]
root.val = 1
while queue:
s = queue.pop(0)
if s.left:
queue.append(s.left)
s.left.val = s.val +1
if s.right:
queue.append(s.right)
s.right.val = s.val +1
if s.left is None and s.right is None:
return s.val | minimum-depth-of-binary-tree | [Python] 99% Faster Solution | jiarow | 0 | 10 | minimum depth of binary tree | 111 | 0.437 | Easy | 832 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2715975/some-recursion | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
c = set()
def lol(r,x):
if r:
lol(r.left,x+1)
lol(r.right,x+1)
else:
return
if not r.left and not r.right:
c.add(x)
lol(root,1)
return min(c) | minimum-depth-of-binary-tree | some recursion | hibit | 0 | 3 | minimum depth of binary tree | 111 | 0.437 | Easy | 833 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2617787/Python-currentCount-solution-O(n)-time-complexity-and-O(h)-space-complexity. | class Solution:
def minDepth(self, root):
if root == None:
return 0
def DFS(root, mn = 100001, currentCount = 0):
if root == None:
return mn
currentCount += 1
if root.left == None and root.right == None and currentCount < mn:
mn = currentCount
left = DFS(root.left, mn, currentCount)
right = DFS(root.right, mn, currentCount)
if left < right:
return left
return right
return DFS(root) | minimum-depth-of-binary-tree | Python currentCount solution, O(n) time complexity and O(h) space complexity. | OsamaRakanAlMraikhat | 0 | 34 | minimum depth of binary tree | 111 | 0.437 | Easy | 834 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2499129/Python-Concise-BFS-Solution-O(logN) | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
# we should solve this using bfs, since the node
# we are trying to find is closes to the root
if root is None:
return 0
queue = [(root, 1)]
while queue:
# pop the most recent node
current, level = queue.pop(0)
# check whether it has no children
if current.left is None and current.right is None:
return level
# insert children
if current.left is not None:
queue.append((current.left, level+1))
if current.right is not None:
queue.append((current.right, level+1)) | minimum-depth-of-binary-tree | [Python] - Concise BFS Solution - O(logN) | Lucew | 0 | 79 | minimum depth of binary tree | 111 | 0.437 | Easy | 835 |
https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2312822/Python-or-BFS | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
import queue
if not root:
return 0
q = queue.Queue()
q.put((1, root))
while not q.empty():
level, node = q.get()
if not node.left and not node.right:
return level
if node.left:
q.put((level+1, node.left))
if node.right:
q.put((level+1, node.right)) | minimum-depth-of-binary-tree | Python | BFS | Sonic0588 | 0 | 88 | minimum depth of binary tree | 111 | 0.437 | Easy | 836 |
https://leetcode.com/problems/path-sum/discuss/2658792/Python-Elegant-and-Short-or-DFS | class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def hasPathSum(self, root: Optional[TreeNode], target: int) -> bool:
if root is None:
return False
if root.left is None and root.right is None:
return target == root.val
return self.hasPathSum( root.left, target - root.val) or \
self.hasPathSum(root.right, target - root.val) | path-sum | Python Elegant & Short | DFS | Kyrylo-Ktl | 10 | 422 | path sum | 112 | 0.477 | Easy | 837 |
https://leetcode.com/problems/path-sum/discuss/2432844/Very-Easy-oror-100-oror-3-Line-oror-Explained-(Java-C%2B%2B-Python-JS-C-Python3) | class Solution(object):
def hasPathSum(self, root, targetSum):
# If the tree is empty i.e. root is NULL, return false...
if root is None: return 0
# If there is only a single root node and the value of root node is equal to the targetSum...
if root.val == targetSum and (root.left is None and root.right is None): return 1
# Call the same function recursively for left and right subtree...
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val) | path-sum | Very Easy || 100% || 3 Line || Explained (Java, C++, Python, JS, C, Python3) | PratikSen07 | 8 | 442 | path sum | 112 | 0.477 | Easy | 838 |
https://leetcode.com/problems/path-sum/discuss/2432844/Very-Easy-oror-100-oror-3-Line-oror-Explained-(Java-C%2B%2B-Python-JS-C-Python3) | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
# If the tree is empty i.e. root is NULL, return false...
if root is None: return 0
# If there is only a single root node and the value of root node is equal to the targetSum...
if root.val == targetSum and (root.left is None and root.right is None): return 1
# Call the same function recursively for left and right subtree...
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val) | path-sum | Very Easy || 100% || 3 Line || Explained (Java, C++, Python, JS, C, Python3) | PratikSen07 | 8 | 442 | path sum | 112 | 0.477 | Easy | 839 |
https://leetcode.com/problems/path-sum/discuss/2658457/1-line-Python | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
return (root.val == targetSum) if (root and not root.left and not root.right) else (root and (self.hasPathSum(root.right, targetSum - root.val) or self.hasPathSum(root.left, targetSum - root.val))) | path-sum | 1-line Python | alex391a | 7 | 422 | path sum | 112 | 0.477 | Easy | 840 |
https://leetcode.com/problems/path-sum/discuss/2176648/Python3-short-4lines-DFS | class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
if root.val == sum and not root.left and not root.right:
return True
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val) | path-sum | π Python3 short 4lines DFS | Dark_wolf_jss | 4 | 51 | path sum | 112 | 0.477 | Easy | 841 |
https://leetcode.com/problems/path-sum/discuss/1583269/Python3-Easy-Fast-Recursive-Solution | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root: return False
if root and not root.left and not root.right: return root.val == targetSum
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val) | path-sum | Python3 Easy, Fast, Recursive Solution | DamonHolland | 4 | 437 | path sum | 112 | 0.477 | Easy | 842 |
https://leetcode.com/problems/path-sum/discuss/2329145/Extremely-modular-(minimal-code)-python3-solution | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root: return False
if not root.left and not root.right and root.val == targetSum: return True
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val) | path-sum | Extremely modular (minimal code) python3 solution | byusuf | 2 | 36 | path sum | 112 | 0.477 | Easy | 843 |
https://leetcode.com/problems/path-sum/discuss/2287814/oror-Pythonoror-FASTEST-AND-SIMPLESToror-7-liner-ororrecursiveoror-Easy-to-Understand | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def dfs(node,sum):
if not node: return False #base case for null node
if sum+node.val == targetSum and not node.left and not node.right: return True #when we find the ans
lt, rt = dfs(node.left,sum+node.val), dfs(node.right,sum+node.val) #recursive steps
return lt or rt
return dfs(root,0) | path-sum | β
|| Python|| FASTEST AND SIMPLEST|| 7-liner ||recursive|| Easy to Understand | HarshVardhan71 | 2 | 72 | path sum | 112 | 0.477 | Easy | 844 |
https://leetcode.com/problems/path-sum/discuss/2287814/oror-Pythonoror-FASTEST-AND-SIMPLESToror-7-liner-ororrecursiveoror-Easy-to-Understand | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def dfs(node,sum):
if not node:return False #base case for null node
if sum+node.val==targetSum and not node.left and not node.right:return True #when we find the ans
lt=dfs(node.left,sum+node.val)
if lt:
return True
else:
rt=dfs(node.right,sum+node.val)
return rt
return dfs(root,0) | path-sum | β
|| Python|| FASTEST AND SIMPLEST|| 7-liner ||recursive|| Easy to Understand | HarshVardhan71 | 2 | 72 | path sum | 112 | 0.477 | Easy | 845 |
https://leetcode.com/problems/path-sum/discuss/1658579/Python-Simple-recursive-DFS-explained | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root: return False
res = 0
def dfs(node):
if not node: return 0
nonlocal res
res += node.val
# recursively check for both the left
# and the right subtrees until we find
# a leaf on the path and the sum matches
# if so; we can safely return True back up
if node.left and dfs(node.left): return True
if node.right and dfs(node.right): return True
# somewhere down the recursion, we found
# a leaf node (a complete path), now return
# True if the rolling sum (res) == targetSum
if not node.left and not node.right:
if res == targetSum:
return True
# here, we're basically backtracking
# up the tree, so for example, from eg 1
# we're at node 7 (leaf) and we realise the
# sum of this path isn't the one we're looking
# for, we'll not return anything for the dfs
# call for node 7, so we just remove it from
# the rolling sum which becomes the sum until node 11
# so we can continue fwd to node 2 and so on
res -= node.val
return dfs(root) | path-sum | [Python] Simple recursive DFS explained | buccatini | 2 | 189 | path sum | 112 | 0.477 | Easy | 846 |
https://leetcode.com/problems/path-sum/discuss/1482571/Python-Clean-Recursive-DFS | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def dfs(node = root, total = 0):
if not node:
return False
total += node.val
if not (node.left or node.right) and total == targetSum:
return True
return dfs(node.left, total) or dfs(node.right, total)
return dfs() | path-sum | [Python] Clean Recursive DFS | soma28 | 2 | 189 | path sum | 112 | 0.477 | Easy | 847 |
https://leetcode.com/problems/path-sum/discuss/2661418/Python-easy-recursion-solution | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root: return False
targetSum -= root.val
return not (targetSum or root.left or root.right) or \
self.hasPathSum(root.left, targetSum) or \
self.hasPathSum(root.right, targetSum) | path-sum | Python easy recursion solution | AgentIvan | 1 | 14 | path sum | 112 | 0.477 | Easy | 848 |
https://leetcode.com/problems/path-sum/discuss/2659426/oror-Python-easy-DFS-solution-oror | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
ans = [False]
def tree_traversal(root, curr_sum, ans):
curr_sum += root.val
if root.left is None and root.right is None:
if curr_sum == targetSum:
ans[0] = True
if root.left:
tree_traversal(root.left, curr_sum, ans)
if root.right:
tree_traversal(root.right, curr_sum, ans)
if root:
tree_traversal(root, 0, ans)
return ans[0] | path-sum | π― || Python easy DFS solution || π― | parth_panchal_10 | 1 | 100 | path sum | 112 | 0.477 | Easy | 849 |
https://leetcode.com/problems/path-sum/discuss/2658490/Python-Iterative-DFS-oror-Faster-than-99.90 | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root: return False
stack = [[root, root.val]]
while stack:
node, total = stack.pop()
if total == targetSum and node.left is None and node.right is None: return True
if node.right: stack.append([node.right, total + node.right.val])
if node.left: stack.append([node.left, total + node.left.val])
return False | path-sum | [Python] Iterative DFS || Faster than 99.90% | sreenithishb | 1 | 46 | path sum | 112 | 0.477 | Easy | 850 |
https://leetcode.com/problems/path-sum/discuss/2657708/4-lines-Python-Javascript | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root: return False
targetSum -= root.val
# leaf node
if root.left is root.right: return targetSum == 0
return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum) | path-sum | 4 lines Python / Javascript | SmittyWerbenjagermanjensen | 1 | 54 | path sum | 112 | 0.477 | Easy | 851 |
https://leetcode.com/problems/path-sum/discuss/2484453/python-simple-solution-using-DFS | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if(not root):
return False
if(root.val == targetSum and root.left == None and root.right == None):
return True
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val) | path-sum | python simple solution using DFS | rajitkumarchauhan99 | 1 | 48 | path sum | 112 | 0.477 | Easy | 852 |
https://leetcode.com/problems/path-sum/discuss/1923955/Python-Fast-Recursive-Solution | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
flag = [False]
def dfs(tree, num):
if not tree:
return
if tree.left is None and tree.right is None:
if tree.val + num == targetSum:
flag[0] = True
dfs(tree.left, num + tree.val)
dfs(tree.right, num + tree.val)
dfs(root, 0)
return flag[0] | path-sum | Python Fast Recursive Solution | Hejita | 1 | 171 | path sum | 112 | 0.477 | Easy | 853 |
https://leetcode.com/problems/path-sum/discuss/1347938/Easy-Fast-Recursive-Python-Solution-using-DFS%2Bstack-(Faster-than-100) | class Solution:
def DFS(self,root):
if root:
self.path.append(root.val)
if not root.left and not root.right:
a = self.path.copy()
if sum(a) == self.targetSum:
self.has_sum += 1
else:
self.DFS(root.left)
self.DFS(root.right)
self.path.pop()
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
self.path = []
self.has_sum = 0
self.targetSum = targetSum
self.DFS(root)
if self.has_sum:
return True
else:
return False | path-sum | Easy, Fast Recursive Python Solution using DFS+stack (Faster than 100%) | the_sky_high | 1 | 168 | path sum | 112 | 0.477 | Easy | 854 |
https://leetcode.com/problems/path-sum/discuss/1235116/Python-Solutions.-Iterative-recursive-DFS | class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
# Recursive dfs.
# Accumulate the number as you traverse the tree and compare with targetSum
# T: O(N)
# S: O(N)
return self.dfs(root, targetSum, 0)
def dfs(self, root, targetSum, total):
if not root:
return False
total += root.val
#print(total)
if not root.left and not root.right:
return total == targetSum
return self.dfs(root.left, targetSum, total) or self.dfs(root.right, targetSum, total)
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
# Iterative DFS
# Same logic
# T: O(N)
# S: O(N)
if not root:
return False
stack = [root]
total = root.val
while stack:
node = stack.pop()
#print(node.val)
if node.left:
node.left.val += node.val
stack.append(node.left)
if node.right:
node.right.val += node.val
stack.append(node.right)
if not node.right and not node.left:
if node.val == targetSum:
return True
return False
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
# Optimized recursive DFS
# Instead of accumulation, we substract the value of node from the targetSum
# T: O(N)
# S: O(N)
if not root:
return False
targetSum -= root.val
if not root.left and not root.right:
return targetSum == 0
return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum) | path-sum | Python Solutions. Iterative, recursive DFS | treksis | 1 | 187 | path sum | 112 | 0.477 | Easy | 855 |
https://leetcode.com/problems/path-sum/discuss/865160/Python3-recursive-solution-(beats-97) | class Solution:
def hasPathSum(self, node: TreeNode, num: int) -> bool:
if node is None:
return False
if not node.right and not node.left:
return node.val == num
return self.hasPathSum(node.left, num - node.val) or self.hasPathSum(node.right, num - node.val) | path-sum | Python3 recursive solution (beats 97%) | n0execution | 1 | 269 | path sum | 112 | 0.477 | Easy | 856 |
https://leetcode.com/problems/path-sum/discuss/801559/(Python)-A-very-simple-recursive-solution | class Solution:
def hasPathSum(self, root: TreeNode, rsum: int) -> bool:
if root == None:
return False
if root.val == rsum and root.left is None and root.right is None:
return True
return (self.hasPathSum(root.left, rsum - root.val) or self.hasPathSum(root.right, rsum - root.val)) | path-sum | (Python) A very simple recursive solution | Aishnupur | 1 | 99 | path sum | 112 | 0.477 | Easy | 857 |
https://leetcode.com/problems/path-sum/discuss/484125/Python-3-(beats-~99)-(nine-lines)-(DFS) | class Solution:
def hasPathSum(self, R: TreeNode, S: int) -> bool:
P, B = [], [0]
def dfs(N):
if N == None or B[0]: return
P.append(N.val)
if (N.left,N.right) == (None,None) and sum(P) == S: B[0] = 1
else: dfs(N.left), dfs(N.right)
P.pop()
dfs(R)
return B[0]
- Junaid Mansuri
- Chicago, IL | path-sum | Python 3 (beats ~99%) (nine lines) (DFS) | junaidmansuri | 1 | 525 | path sum | 112 | 0.477 | Easy | 858 |
https://leetcode.com/problems/path-sum/discuss/429483/Python3-recursive-solution-(99.37) | class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root: return False #non-leaf
if not root.left and not root.right: return root.val == sum #leaf
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val) | path-sum | Python3 recursive solution (99.37%) | ye15 | 1 | 165 | path sum | 112 | 0.477 | Easy | 859 |
https://leetcode.com/problems/path-sum/discuss/429483/Python3-recursive-solution-(99.37) | class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root: return sum == 0
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val) | path-sum | Python3 recursive solution (99.37%) | ye15 | 1 | 165 | path sum | 112 | 0.477 | Easy | 860 |
https://leetcode.com/problems/path-sum/discuss/429483/Python3-recursive-solution-(99.37) | class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
def fn(node, x):
if not node: return False #non-leaf
if not node.left and not node.right: return node.val == x #leaf node
return fn(node.left, x-node.val) or fn(node.right, x-node.val)
return fn(root, sum) | path-sum | Python3 recursive solution (99.37%) | ye15 | 1 | 165 | path sum | 112 | 0.477 | Easy | 861 |
https://leetcode.com/problems/path-sum/discuss/429483/Python3-recursive-solution-(99.37) | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
stack = [(root, 0)]
while stack:
node, val = stack.pop()
if node:
val += node.val
if not node.left and not node.right and val == targetSum: return True
if node.right: stack.append((node.right, val))
if node.left: stack.append((node.left, val))
return False | path-sum | Python3 recursive solution (99.37%) | ye15 | 1 | 165 | path sum | 112 | 0.477 | Easy | 862 |
https://leetcode.com/problems/path-sum/discuss/366622/Python-recursive-and-iterative-using-pre-order | class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
sum -= root.val
if sum == 0 and not root.left and not root.right:
return True
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum) | path-sum | Python recursive and iterative using pre-order | amchoukir | 1 | 234 | path sum | 112 | 0.477 | Easy | 863 |
https://leetcode.com/problems/path-sum/discuss/366622/Python-recursive-and-iterative-using-pre-order | class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
stack = [(root, sum)]
while stack:
node, sum = stack.pop()
sum -= node.val
if sum == 0 and not node.left and not node.right:
return True
# Appending right before left to pop left first
if node.right:
stack.append((node.right, sum))
if node.left:
stack.append((node.left, sum))
return False | path-sum | Python recursive and iterative using pre-order | amchoukir | 1 | 234 | path sum | 112 | 0.477 | Easy | 864 |
https://leetcode.com/problems/path-sum/discuss/2827790/simple-python-oror-dfs | class Solution:
def hasPathSum(self, root: Optional[TreeNode], target_sum: int) -> bool:
# if root doesn't exist
if not root:
return False
# update target_sum
target_sum -= root.val
# if leaf node and target_sum reached
if (not root.left) and (not root.right) and (target_sum == 0):
return True
# run on left and right children
return self.hasPathSum(root.left, target_sum) or self.hasPathSum(root.right, target_sum) | path-sum | simple python || dfs | wduf | 0 | 9 | path sum | 112 | 0.477 | Easy | 865 |
https://leetcode.com/problems/path-sum/discuss/2802803/Python-OneLiner | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
return False if not root else (root.val == targetSum and not root.left and not root.right) or self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val) | path-sum | Python OneLiner | ryankert | 0 | 2 | path sum | 112 | 0.477 | Easy | 866 |
https://leetcode.com/problems/path-sum/discuss/2660665/Python3!-As-short-as-it-gets! | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root == None:
return False
if root.left is None and root.right is None:
return targetSum == root.val
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val) | path-sum | πPython3! As short as it gets! | aminjun | 0 | 28 | path sum | 112 | 0.477 | Easy | 867 |
https://leetcode.com/problems/path-sum/discuss/2660572/Python-Solution | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def traversal(node, currentSum):
if not node: return False
c = currentSum + node.val
if node.left and node.right:
return traversal(node.left, c) or traversal(node.right, c)
elif node.left:
return traversal(node.left, c)
elif node.right:
return traversal(node.right, c)
else:
return c == targetSum
return traversal(root, 0) | path-sum | Python Solution | AxelDovskog | 0 | 5 | path sum | 112 | 0.477 | Easy | 868 |
https://leetcode.com/problems/path-sum/discuss/2659969/94-Faster-than-Solution-or-Easy-to-Understand-or-Python | class Solution(object):
def dfs(self, root, sum_, target):
if not root: return False
if root.left is None and root.right is None and (sum_ + root.val) == target: return True
return self.dfs(root.left, sum_ + root.val, target) or self.dfs(root.right, sum_ + root.val, target)
def hasPathSum(self, root, targetSum):
return self.dfs(root, 0, targetSum) | path-sum | 94% Faster than Solution | Easy to Understand | Python | its_krish_here | 0 | 66 | path sum | 112 | 0.477 | Easy | 869 |
https://leetcode.com/problems/path-sum/discuss/2659678/DFS | class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
f = False
def util(root, c):
nonlocal f
if root:
c += root.val
util(root.left, c)
util(root.right, c)
if not root.left and not root.right and c == targetSum:
f= True
util(root, 0)
return f | path-sum | DFS | jaisalShah | 0 | 3 | path sum | 112 | 0.477 | Easy | 870 |
https://leetcode.com/problems/path-sum-ii/discuss/484120/Python-3-(beats-~100)-(nine-lines)-(DFS) | class Solution:
def pathSum(self, R: TreeNode, S: int) -> List[List[int]]:
A, P = [], []
def dfs(N):
if N == None: return
P.append(N.val)
if (N.left,N.right) == (None,None) and sum(P) == S: A.append(list(P))
else: dfs(N.left), dfs(N.right)
P.pop()
dfs(R)
return A
- Junaid Mansuri
- Chicago, IL | path-sum-ii | Python 3 (beats ~100%) (nine lines) (DFS) | junaidmansuri | 9 | 2,200 | path sum ii | 113 | 0.567 | Medium | 871 |
https://leetcode.com/problems/path-sum-ii/discuss/2615820/Clean-Fast-Python3-or-BFS | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if root is None:
return []
q, paths = deque([(root, targetSum, [])]), []
while q:
cur, target, path = q.pop()
if not (cur.left or cur.right) and cur.val == target:
paths.append(path + [cur.val])
else:
if cur.left:
q.appendleft((cur.left, target - cur.val, path + [cur.val]))
if cur.right:
q.appendleft((cur.right, target - cur.val, path + [cur.val]))
return paths | path-sum-ii | Clean, Fast Python3 | BFS | ryangrayson | 8 | 502 | path sum ii | 113 | 0.567 | Medium | 872 |
https://leetcode.com/problems/path-sum-ii/discuss/2615994/python3-or-very-easy-or-explained-or-tree | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
self.targetSum, self.ans = targetSum, [] # variable initialization
self.get_path_sum(root, 0, []) # calling function get path sum
return self.ans # return answer
def get_path_sum(self, root, psum, path):
if not root: return None # if not root return None
if not root.left and not root.right: # if curr node is leaf
if root.val + psum == self.targetSum: # if path sum from root to leaf = target sum
path.append(root.val) # append node value to path
self.ans.append([e for e in path]) # add path to ans list
path.pop(-1) # remove node value from path
return; # return
path.append(root.val) # append node value to path
self.get_path_sum(root.left, psum + root.val, path) # left traversal
self.get_path_sum(root.right, psum + root.val, path)# right traversal
path.pop(-1) # remove node value from path | path-sum-ii | python3 | very easy | explained | tree | H-R-S | 2 | 145 | path sum ii | 113 | 0.567 | Medium | 873 |
https://leetcode.com/problems/path-sum-ii/discuss/2362977/Easy-dfs-python-solution | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
# Simple dfs solution
# we have to check both left call, and right call and
# insert path into the final result i.e. res
def helper(root,targetsum,path,res,csum):
if root is None:
return
if root.left == None and root.right==None:
if targetSum==csum+root.val:
path+=[root.val]
return res.append(path[:])
helper(root.left,targetSum,path+[root.val],res,csum+root.val)
helper(root.right,targetSum,path+[root.val],res,csum+root.val)
path=[]
res=[]
helper(root,targetSum,path,res,0)
return res | path-sum-ii | Easy dfs python solution | Aniket_liar07 | 2 | 92 | path sum ii | 113 | 0.567 | Medium | 874 |
https://leetcode.com/problems/path-sum-ii/discuss/2320926/Python3-standard-DFS-solution | class Solution:
def pathSum(self, root: Optional[TreeNode], target: int) -> List[List[int]]:
result = []
def dfs(root, target, path):
if not root:
return
if not root.left and not root.right and target - root.val == 0:
result.append(path + [root.val])
return
dfs(root.left, target - root.val, path + [root.val])
dfs(root.right, target - root.val, path + [root.val])
dfs(root, target, [])
return result | path-sum-ii | π Python3 standard DFS solution | Dark_wolf_jss | 2 | 37 | path sum ii | 113 | 0.567 | Medium | 875 |
https://leetcode.com/problems/path-sum-ii/discuss/1079961/Elegant-Python-DFS-solution-faster-than-99.90 | class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
def dfs(node, total = 0, path = []):
if not node: return
path.append(node.val)
total += node.val
if not (node.left or node.right) and total == targetSum:
paths.append(list(path))
else:
dfs(node.left, total), dfs(node.right, total)
total -= path.pop()
paths = []
dfs(root)
return paths | path-sum-ii | Elegant Python DFS solution, faster than 99.90% | 111989 | 2 | 302 | path sum ii | 113 | 0.567 | Medium | 876 |
https://leetcode.com/problems/path-sum-ii/discuss/2441342/Python3-breath-first-search-solution-easy-to-understand | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if root is None: # Corner case
return []
# Initialize variables
result = []
deq = deque()
# Start traversal
# Every element of deque is a state describing current node
# As a state we need the following: node itself, remaining sum, path from the root
deq.append((root, targetSum, []))
# Breath-first-search part
while deq:
node, left_sum, path = deq.popleft()
left_sum -= node.val
path.append(node.val)
if node.left or node.right: # Try to go into children
if node.left:
deq.append((node.left, left_sum, path.copy()))
if node.right:
deq.append((node.right, left_sum, path.copy()))
elif left_sum == 0: # End of a traversal, check if the total path sum is equal to 0
result.append(path) # Put path values into the result
return result | path-sum-ii | Python3, breath first search solution, easy to understand | NonameDeadinside | 1 | 30 | path sum ii | 113 | 0.567 | Medium | 877 |
https://leetcode.com/problems/path-sum-ii/discuss/1383147/Python3-dfs | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
ans = []
if root:
mp = {root: None}
stack = [(root, 0)]
while stack:
node, val = stack.pop()
val += node.val
if node.left:
mp[node.left] = node
stack.append((node.left, val))
if node.right:
mp[node.right] = node
stack.append((node.right, val))
if not node.left and not node.right and val == targetSum:
path = []
while node:
path.append(node.val)
node = mp[node]
ans.append(path[::-1])
return ans | path-sum-ii | [Python3] dfs | ye15 | 1 | 38 | path sum ii | 113 | 0.567 | Medium | 878 |
https://leetcode.com/problems/path-sum-ii/discuss/1383097/Python-10-lines-DFS | class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
self.ans = []
def dfs(node, path):
if not node: return
if not node.left and not node.right:
if sum(path + [node.val]) == targetSum: self.ans.append(path + [node.val])
return
dfs(node.left, path + [node.val])
dfs(node.right, path + [node.val])
dfs(root, [])
return self.ans | path-sum-ii | Python 10 lines DFS | SmittyWerbenjagermanjensen | 1 | 155 | path sum ii | 113 | 0.567 | Medium | 879 |
https://leetcode.com/problems/path-sum-ii/discuss/1369835/DFS-using-generator-with-5-lines-in-Python-3 | class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
def dfs(n: TreeNode, s: int):
if (None, None) == (n.left, n.right) and s == targetSum:
yield [n.val]
else:
yield from ([n.val] + path for c in (n.left, n.right) if c for path in dfs(c, (s + c.val)))
return list(dfs(root, root.val)) if root else [] | path-sum-ii | DFS using generator with 5 lines in Python 3 | mousun224 | 1 | 38 | path sum ii | 113 | 0.567 | Medium | 880 |
https://leetcode.com/problems/path-sum-ii/discuss/571907/Elegant-solution-using-a-single-function-Python-DFS | class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
if not root: return []
if not root.left and not root.right:
# leaf node
if root.val == sum:
return [[root.val]]
else:
return []
left = self.pathSum(root.left, sum-root.val)
right = self.pathSum(root.right, sum-root.val)
left = list(map(lambda xs: [root.val, *xs], left))
right = list(map(lambda xs: [root.val, *xs], right))
return left + right | path-sum-ii | Elegant solution using a single function [Python] [DFS] | 1337_baka | 1 | 56 | path sum ii | 113 | 0.567 | Medium | 881 |
https://leetcode.com/problems/path-sum-ii/discuss/2794919/Python3-recursive-solution | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
curr = [] # contains current traversing path
out = [] # contains all found paths
def t(node):
if not node: return # node is null
curr.append(node.val) # append this node to current path
# if node is a leaf and path is valid, copy it to <out>
if (not node.left) and (not node.right) and sum(curr)==targetSum:
out.append(curr.copy())
else:
t(node.left) # traverse left tree
t(node.right) # traverse right tree
curr.pop() # remove this node from current path and return
t(root)
return out | path-sum-ii | Python3 recursive solution | lucabonagd | 0 | 3 | path sum ii | 113 | 0.567 | Medium | 882 |
https://leetcode.com/problems/path-sum-ii/discuss/2726523/Python-3-dfs-recursive-sol. | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
res = []
def dfs(v, path, pathsum):
if not v:
return
path.append(v.val)
pathsum += v.val
if not v.left and not v.right and pathsum == targetSum:
res.append(path[:])
dfs(v.left, path, pathsum)
dfs(v.right, path, pathsum)
path.pop()
dfs(root, [], 0)
return res | path-sum-ii | Python 3 dfs recursive sol. | pranjalmishra334 | 0 | 8 | path sum ii | 113 | 0.567 | Medium | 883 |
https://leetcode.com/problems/path-sum-ii/discuss/2700104/Simple-Beginner-Friendly-Approach-or-DFS-or-O(N)-or-O(N) | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
self.res = []
self.dfs(root, [], targetSum)
return self.res
def dfs(self, root, path, targetSum):
if not root:
return
if not root.left and not root.right:
if root.val == targetSum:
self.res.append(path + [root.val])
return
self.dfs(root.left, path + [root.val], targetSum - root.val)
self.dfs(root.right, path + [root.val], targetSum - root.val) | path-sum-ii | Simple Beginner Friendly Approach | DFS | O(N) | O(N) | sonnylaskar | 0 | 11 | path sum ii | 113 | 0.567 | Medium | 884 |
https://leetcode.com/problems/path-sum-ii/discuss/2645451/Python-(Faster-than-98)-or-DFS | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
ans = []
def dfs(node, pathsum, path):
if node:
pathsum += node.val
path.append(node.val)
if not node.left and not node.right:
if pathsum == targetSum:
ans.append(path)
else:
dfs(node.left, pathsum, path.copy())
dfs(node.right, pathsum, path.copy())
dfs(root, 0, [])
return ans | path-sum-ii | Python (Faster than 98%) | DFS | KevinJM17 | 0 | 4 | path sum ii | 113 | 0.567 | Medium | 885 |
https://leetcode.com/problems/path-sum-ii/discuss/2635875/Easy-Python3-solution-using-recursion | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
paths = []
def traverse(path, node):
if(not node):
return
if(node.left == None and node.right == None):
if(sum(path) + node.val != targetSum):
return
else:
paths.append(path+[node.val])
return
else:
traverse(path+[node.val],node.left)
traverse(path+[node.val],node.right)
traverse([], root)
return paths | path-sum-ii | Easy Python3 solution using recursion | PranavBharadwaj1305 | 0 | 8 | path sum ii | 113 | 0.567 | Medium | 886 |
https://leetcode.com/problems/path-sum-ii/discuss/2618669/Clean-8-line-DFS-in-Python-3 | class Solution:
def pathSum(self, root: Optional[TreeNode], target: int) -> List[List[int]]:
def dfs(n: TreeNode = root, s=0):
s += n.val
if (None, None) == (n.left, n.right) and s == target:
yield [n.val]
else:
for c in filter(None, (n.left, n.right)):
yield from ([n.val] + path for path in dfs(c, s))
return list(dfs(root)) if root else [] | path-sum-ii | Clean 8-line DFS in Python 3 | mousun224 | 0 | 18 | path sum ii | 113 | 0.567 | Medium | 887 |
https://leetcode.com/problems/path-sum-ii/discuss/2618375/Easy-to-read | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
ans = []
def dfs(node, path, ans):
path.append(node.val)
if node.left == None and node.right == None:
if sum(path) == targetSum:
ans.append(path)
return
if node.right : dfs(node.right, path[:], ans)
if node.left : dfs(node.left, path[:], ans)
return
if root: dfs(root, [], ans)
return ans | path-sum-ii | Easy to read | TheFlyingTurtle46 | 0 | 13 | path sum ii | 113 | 0.567 | Medium | 888 |
https://leetcode.com/problems/path-sum-ii/discuss/2618071/90-Faster-oror-Simple-Python-Solution | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if root is None:
return []
if root.left is None and root.right is None:
if targetSum-root.val==0:
return [[root.val]]
else:
return []
ans = []
if root.left:
left_ans = self.pathSum(root.left, targetSum-root.val)
for l in left_ans:
ans.append([root.val]+l)
if root.right:
right_ans = self.pathSum(root.right, targetSum-root.val)
for l in right_ans:
ans.append([root.val]+l)
return ans | path-sum-ii | 90% Faster π₯ || Simple Python Solution | wilspi | 0 | 8 | path sum ii | 113 | 0.567 | Medium | 889 |
https://leetcode.com/problems/path-sum-ii/discuss/2617988/python3-short-and-simple | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root: return []
self.ans = []
def dfs(node, path, t):
if t == 0 and not node.left and not node.right: self.ans.append(path)
if node.left: dfs(node.left, path+[node.left.val], t-node.left.val)
if node.right: dfs(node.right, path+[node.right.val], t-node.right.val)
dfs(root, [root.val], targetSum-root.val)
return self.ans | path-sum-ii | python3, short and simple | pjy953 | 0 | 3 | path sum ii | 113 | 0.567 | Medium | 890 |
https://leetcode.com/problems/path-sum-ii/discuss/2617260/Python-Solution-DFS | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
def dfs(node, node_path=[]):
if not node: return
node_path.append(node.val) # append value to the path
if (not node.left) and (not node.right): # check node is leaf node
if sum(node_path) == targetSum: # add the path to answer if sum of path == target
answer.append(node_path.copy())
else: # traverse the node
dfs(node.left, node_path)
dfs(node.right, node_path)
node_path.pop() # pop visited nodes from the path
answer = []
dfs(root)
return answer | path-sum-ii | Python Solution DFS | remenraj | 0 | 20 | path sum ii | 113 | 0.567 | Medium | 891 |
https://leetcode.com/problems/path-sum-ii/discuss/2617175/Python-Faster-than-98 | class Solution:
paths = []
def traversal(self, node, currentPath):
c = currentPath.copy()
c.append(node.val)
if not node.left and not node.right:
self.paths.append(c)
else:
if node.left:
self.traversal(node.left, c)
if node.right:
self.traversal(node.right, c)
def pathSum(self, root, targetSum: int):
self.paths = []
if not root:
return
output = []
self.traversal(root, [])
for path in self.paths:
if sum(path) == targetSum:
output.append(path)
return output | path-sum-ii | Python Faster than 98% | AxelDovskog | 0 | 9 | path sum ii | 113 | 0.567 | Medium | 892 |
https://leetcode.com/problems/path-sum-ii/discuss/2616767/python-easy-peasy-solution-using-dfs-iteration | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root:
return []
res=[]
stk=[[root,root.val,[root.val]]]
while stk:
temp=stk.pop()
if not temp[0].left and not temp[0].right and temp[1]==targetSum:
res.append(temp[2])
if temp[0].left:
stk.append([temp[0].left,temp[1]+temp[0].left.val,temp[2]+[temp[0].left.val]])
if temp[0].right:
stk.append([temp[0].right,temp[1]+temp[0].right.val,temp[2]+[temp[0].right.val]])
return res | path-sum-ii | python easy-peasy solution using dfs iteration | benon | 0 | 20 | path sum ii | 113 | 0.567 | Medium | 893 |
https://leetcode.com/problems/path-sum-ii/discuss/2616642/Python-Simple-Python-Solution-Using-DFS-(Recursion)-and-Backtracking | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
self.result_path = []
def DFS(node,target_Sum, current_path):
if node == None:
return []
current_path.append(node.val)
if node.left is None and node.right is None and sum(current_path) == target_Sum:
self.result_path.append(list(current_path))
DFS(node.left, target_Sum, current_path)
DFS(node.right,target_Sum, current_path)
current_path.pop()
DFS(root,targetSum, [])
return self.result_path | path-sum-ii | [ Python ] β
β
Simple Python Solution Using DFS (Recursion) and Backtracking π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 0 | 8 | path sum ii | 113 | 0.567 | Medium | 894 |
https://leetcode.com/problems/path-sum-ii/discuss/2616173/Python-Solution-or-Recursion-or-Easy | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
ans=[]
def helper(root, path):
if root is None:
return []
if root.left is None and root.right is None:
if sum(path)+root.val==targetSum:
path.append(root.val)
ans.append(path[:])
path.pop()
helper(root.left, path+[root.val])
helper(root.right, path+[root.val])
helper(root, [])
return ans | path-sum-ii | Python Solution | Recursion | Easy | Siddharth_singh | 0 | 22 | path sum ii | 113 | 0.567 | Medium | 895 |
https://leetcode.com/problems/path-sum-ii/discuss/2615839/Python-or-DFS | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
self.answer = []
def traverse(root, targetSum, path, currSum):
if not root:
return
path.append(root.val)
currSum += root.val
if not root.left and not root.right and currSum == targetSum:
self.answer.append(path.copy())
traverse(root.left, targetSum, path, currSum)
traverse(root.right, targetSum, path, currSum)
currSum -= path.pop()
return
traverse(root, targetSum, [], 0)
return self.answer | path-sum-ii | Python | DFS | everydayspecial | 0 | 17 | path sum ii | 113 | 0.567 | Medium | 896 |
https://leetcode.com/problems/path-sum-ii/discuss/2532847/93ms-or-Python-solution | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
ans = []
def dfs(node: Optional[TreeNode], arr: List[int], resSum: int):
if node == None:
return
arr.append(node.val);
resSum -= node.val;
if node.left == None and node.right == None and resSum == 0:
ans.append(arr[:])
else:
dfs(node.left, arr, resSum)
dfs(node.right, arr, resSum)
arr.pop()
dfs(root, [], targetSum)
return ans | path-sum-ii | 93ms | Python solution | kitanoyoru_ | 0 | 33 | path sum ii | 113 | 0.567 | Medium | 897 |
https://leetcode.com/problems/path-sum-ii/discuss/2488263/Python-solution-using-DFS-TC-%3A-O(N)-SC%3A-O(N) | class Solution:
def solve(self, root, S , curr , res):
if(not root):
return
curr.append(root.val)
if(root.val == S and not root.left and not root.right):
res.append(list(curr))
#remeber that when append lisi of list convert into a list
self.solve(root.left, S - root.val , curr , res)
self.solve(root.right, S - root.val , curr , res)
#del curr[-1]
curr.pop()
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
res = []
curr = []
self.solve(root , targetSum , curr , res)
return res | path-sum-ii | Python solution using DFS TC : O(N) SC: O(N) | rajitkumarchauhan99 | 0 | 38 | path sum ii | 113 | 0.567 | Medium | 898 |
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2340445/Python-or-intuitive-explained-or-O(1)-space-ignoring-recursion-stack-or-O(n)-time | class Solution:
def __init__(self):
self.prev = None
def flatten(self, root: Optional[TreeNode]) -> None:
if not root: return
self.flatten(root.right)
self.flatten(root.left)
root.right = self.prev
root.left = None
self.prev = root | flatten-binary-tree-to-linked-list | Python | intuitive, explained | O(1) space ignoring recursion stack | O(n) time | mync | 7 | 223 | flatten binary tree to linked list | 114 | 0.612 | Medium | 899 |
Subsets and Splits