Reputation: 149
So I'm just working on some simple tree functions. I'm stumped on the way recursion is working in my code. I know it's probably simple in what I am missing, but hoping someone on here can explain to me in simple terms why my code isn't working the way I want.
So, I'm trying to just trying to do a preorder traversal through a tree and append the node content to a string i declare outside of the preorder function.
t:
1
/ \
2 3
def preorderPrint(t):
tree = "TREE: "
def preorder(tree, string):
if tree is None:
string += f"None "
return
string += f"#{tree.val} "
print(string)
if tree.left:
preorder(tree.left, string)
if tree.right:
preorder(tree.right, string)
preorder(t, tree)
return tree
The output from print statements looks like this:
TREE: #1
TREE: #1 #2
TREE: #1 #3
TREE:
The last print is me printing what is returned from the function call.
So what Im trying to understand is, why do the contents of the string change? I can somewhat see that as it moves up the recursive stack, it doesn't retain its original value, but I'm just confused on what exactly is happening. If anyone can explain, I would greatly appreciate it!
Upvotes: 0
Views: 592
Reputation: 56
If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value. You need to return the string at the end of your function and concatenate the returned value again.
Upvotes: 3
Reputation: 953
you function preorder
does not return any values and does numbers printed inside your recursive function.
consider you first #1
which is true and expected, the next node will be #2
as it is the left node. your code prints it out when the inner function is executing with this arguments preorder(2,'#1')
. after this, there are no left nodes and it will get back to your first node #1
. then it will consider your right node that will be your third answer.
if you want something like #1 #2 #3
, you should return values from your preorder
function and append it to a string variable which comulativly gather your data and print it out when your search is done.
Upvotes: 0