TREES
TREES
Mohd Ayyoob
(M.Tech CSA, IISc Banglore)
Full Binary Tree Complete Binary Tree Perfect Binary Tree
All nodes have All levels except last is filled. A CBT where the last
either 0 children or 2 Last level is left filled level is also filled
Depth of a NODE
• Number of edges from the node to root
• A root has depth 0
Height of a NODE
• Number of edges in the longest path from the node to leaf or
• Maximum number of edges from node to leaf
• A leaf node has height 0
For a BINARY TREE
def fun(t):
a, b = 0, 0
If not t.left and not t.right:
return 0
If t.left:
a = fun(t.left)
If t.right:
b = fun(t.right)
ans = max(a, b) + 1
return ans
def fun(t):
a, b = 0, 0
If not t.left and not t.right:
return 0
If t.left:
a = fun(t.left)
If t.right:
b = fun(t.right)
ans = max(a, b) + 1
return ans
def fun(t):
a, b = 0, 0
If not t.left and not t.right:
return 0
If t.left:
a = fun(t.left)
If t.right:
b = fun(t.right)
ans = max(a, b) + 1
return ans
def fun(t):
a, b = 0, 0
If not t.left and not t.right:
return 0
If t.left:
a = fun(t.left)
If t.right:
b = fun(t.right)
ans = max(a, b) + 1
return ans
def fun(root):
If not root:
return 0
else if root.left is None and root.right is None:
return 2
else:
return 3 + fun(root.left) + func(root.right)
Q4. What does fun(root) return for a given tree?
def fun(root):
If not root:
return 0
else if root.left is None and root.right is None:
return 2
else:
return 3 + fun(root.left) + func(root.right)
Q5. What does checkDEEP(root) return for a given tree?
def checkDEEP(root):
temp = None
If not root :
return None
Enqueue(root)
def checkDEEP(root):
temp = None
If not root :
return None
Enqueue(root)
def maxWidth(root):
if not root:
return 0
Enqueue(root)
j= 0
while not IsEmptyQueue():
i= len(queue)
j= max(j, i)
for _ in range(i):
node = Dequeue()
if node.left:
Enqueue(node.left)
if node.right:
Enqueue(node.right)
return j
Q9. What does maxWidth(root) return for a given tree?
def maxWidth(root):
if not root:
return 0
Enqueue(root)
j= 0
while not IsEmptyQueue():
i= len(queue)
j= max(j, i)
for _ in range(i):
node = Dequeue()
if node.left:
Enqueue(node.left)
if node.right:
Enqueue(node.right)
return j
Q10. What does check(root1, root2) return for a given tree?
def do(t):
if t:
do(t.left)
do(t.right)
t.right, t.left = t.left, t.right
Q12. What does below function?
def do(t):
if t:
do(t.left)
do(t.right)
t.right, t.left = t.left, t.right