Trees Flashcards

(10 cards)

1
Q

Invert Binary Tree

A

root.left, root.right = root.right, root.left
helper(root.left)
helper(root.right)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Maximum Depth of Binary Tree

A

return 1 + max(maxDepth(root.left), maxDepth(root.right))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Diameter of Binary Tree

A

self.diameter = 0

def helper(root):
if root is None: return 0
left = helper(root.left)
right = helper(root.right)
self.diameter = max(self.diameter, left + right)
return 1 + max(left, right)

helper(root)
return self.diameter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Balanced Binary Tree

A

def helper(root):
if root is None: return 0

left  = helper(root.left)
if left == -1: return -1

right = helper(root.right)
if right == -1: return -1

if abs(left-right) > 1: return -1

return 1 + max(left,right)

return helper(root) != -1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Same Tree

A

if p is None and q is None:
return True
elif p is None and q:
return False
elif q is None and p:
return False
else:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Subtree of Another Tree

A

if not root: return False

if sameTree(root, subRoot): return True

return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

LCA

A

def helper(root, p, q):
if root is None: return None
elif root == p: return root
elif root == q: return root

left  = helper(root.left, p, q)
right = helper(root.right, p, q)

if left and right:
    return root
return left if left else right
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Level Order Traversal

A

while qe:
level_size = len(qe)
level = []

for _ in range(level_size):
    node = qe.popleft()
    level.append(node.val)
    if node.left: qe.append(node.left)
    if node.right: qe.append(node.right)

result.append(level)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Count Good Nodes in Binary Tree

A

def helper(root, maxValue):
if root is None:
return
if root.val >= maxValue:
self.counter += 1
helper(root.left, max(maxValue, root.val))
helper(root.right, max(maxValue, root.val))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Validate Binary Search Tree

A

def helper(root, low, high):
if root is None:
return True
if low >= root.val or high <= root.val:
return False
return helper(root.left, low, root.val) and helper(root.right, root.val, high)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly