Documenting LeetCode solving.
Q54
199. Binary Tree Right Side View
Medium. Tree
BFS
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
res = []
q = collections.deque()
q.append(root)
while q:
rightSide = None
qLen = len(q)
for i in range(qLen):
node = q.popleft()
if node:
rightSide = node
q.append(node.left)
q.append(node.right)
if rightSide:
res.append(rightSide.val)
return res
Q55
1448. Count Good Nodes in Binary Tree
Medium. Tree
Preorder traverse.
class Solution:
def goodNodes(self, root: TreeNode) -> int:
def dfs(node, maxVal):
if not node:
return 0
# Preorder
res = 1 if node.val >= maxVal else 0
maxVal = max(maxVal, node.val)
res += dfs(node.left, maxVal)
res += dfs(node.right, maxVal)
return res
return dfs(root, root.val)
Q56
98. Validate Binary Search Tree
Medium. Tree
Keep track of the left and right boundary.
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def valid(node, left, right):
if not node:
return True
if not (node.val > left and node.val < right):
return False
return (valid(node.left, left, node.val) and
valid(node.right, node.val, right))
return valid(root, float("-infinity"), float("infinity"))
ย