'How to make a function that returns all marks on a certain depth of a binary tree in Python
I'm trying to retake my Python exams and i've never really gotten the hang of binary trees.For one exercise i have to make a function that takes an int and a tree as args and returns a list of each node mark on the specified depth.
i have the basic
@dataclass
class Node:
mark: Any
left: Optional['Node']
right: Optional['Node']
to work with. I know how to determine max depth of a binary tree
def maxDepth(node:Node):
if node is None:
return -1
else :
lDepth = maxDepth(node.left)
rDepth = maxDepth(node.right)
if (lDepth > rDepth):
return lDepth+1
else:
return rDepth+1
and tried using that with a while loop to stop at a certain depth.
def layer(n:int,node:Node):
result=[]
depth=maxDepth(node)
while depth != n:
new_depth=maxDepth(node)
result.append(node)
return result
but my code makes no sense. I've also thought if i could make a recursive depth-finding function that also counts each time it's called, but have no idea how to implement that. Any help is welcome, i don't want the direct solution, but if you could point me in the right direction that would be great :)
Solution 1:[1]
I think that something like this might help:
from typing import Any, Optional
class Node:
mark: Any
left: Optional['Node']
right: Optional['Node']
def traverse_tree(node:Node,currentDepth:int,desiredDepth:int):
if node != None:
traverse_tree(node.left,currentDepth+1,desiredDepth)
traverse_tree(node.right,currentDepth+1,desiredDepth)
if currentDepth==desiredDepth:
print(node)
You just have to start off with currentDepth as 0 and this code will traverse the tree, printing those elements with the desired depth.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vorrade - |
