I'm writing a code to execute a weighted tree and make all distances of the edges equal , I want to simplify these statements in just a few lines,, to make it more professional any help ???
class Node:
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.data, end=' ')
print(root.weight)
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.data, end=' ')
print(root.weight)
def new_weights(root):
CodePudding user response:
Your code is not fully clear in terms what you are trying to achieve plus there is no return condition so assuming the unknown I would try to achieve something like this using recursion:
def new_weights(counter = 0, right_weight, left_weight):
if counter < 3:
diff = right_weight - left_weight
if diff> 0:
left_weight = diff
else:
right_weight = (diff * -1)
counter = 1
return new_weights(counter, right_weight, left_weight)
else:
return diff
CodePudding user response:
I see many similar code here, lets try to encapsulate it with functions. Focus on that part
diff=root.right.weight-root.left.weight
if diff> 0:
root.left.weight=root.left.weight diff
else:
root.right.weight=root.right.weight (diff*-1)
Basically here you have some node. Then you check left/right node and update the correct one. We could move it to your class responsible for node
class Node:
def balance(self):
# diff is not needed, as you just set up left to right or otherwise
if root.right
root.right.balance()
if root.left:
root.left.balance()
if root.left and root.right:
if root.right.weight > root.left.weight:
root.left.weight=root.right.weight
else:
root.right.weight=root.left.weight
And now your code could be shortened to:
root.balance()