jweinst1
10/11/2016 - 4:39 AM

additionaltreereplace.py


class Tree:
	
	def __init__(self, value, children):
		self.value = value
		self.children = children
		
	def is_leaf(self):
		return self.children == []
		
		
		

def replace(t, old, new):
	if t.is_leaf():
		if t.value == old:
			t.value = new
			return t 
		else:
			return t
	else:
		for i in range(len(t.children)):
			#Replaces each child node with the return tree from the function
			t.children[i] = replace(t.children[i], old, new)
		return t
		
		
"""   a = Tree(3, [])
=> None
   a.children
=> []
   a.children.append(Tree(1, []))
=> None
   a.children
=> [<Tree object at 0x7f30aa6ea128>]
   a.children.append(Tree(1, []))
=> None
   a.children.append(Tree(1, []))
=> None
   a.children[0].children.append(Tree(1, []))
=> None
   a.value
=> 3
   b = replace(a, 1, 4)
=> None
   b
=> <Tree object at 0x7f30aa6c9198>
   b.value
=> 3
Not a leaf so its not replaced
   b.children[0].value
=> 1
   b.children[1].value
=> 4"""