I have a tuple like this.
t = (5, (3, (20, none, none), (21, none, none)), (10, (1, none, none), none))
I would like to build a tree from it. Tree class look like this.
class TreeNode(object):
def __init__(self,x=None,l=None,r=None):
self.x = x
self.l = l # left node
self.r = r # right node
I am building tree recursively. I check if the current node is None
, then set current node to a new TreeNode
class. But this doesn't work as expected.
def build(current_node, tupl):
if tupl:
if current_node is None:
current_node = TreeNode() # I think this removes link to the trees node.
current_node.x = tupl[0]
build(current_node.l, tupl[1])
build(current_node.r,tupl[2])
here is how I call build function
root = TreeNode() # TreeNode is tree class
build(root,t)
# I try to print the tree level by level but tree only has root node
But this build function works fine.
def build(curr,t):
if t:
curr.x = t[0]
try:
if t[1] is not None:
curr.l = TreeNode()
build(curr.l,t[1])
except Exception:
pass
try:
if t[2] is not None:
curr.r = TreeNode()
build(curr.r,t[2])
except Exception:
pass
I am trying to understand why the first build function is failing.