谁能解释一下 python 代码中的 "printtree" 函数是如何工作的
Can someone explain how the "printtree" function in this python code works
我试图弄清楚如何在 python 中制作二叉树,并在网上找到了这段代码。任何人都可以解释 printtree
函数如何能够打印出所有值
class node:
def __init__(self, data):
self.leftval = None
self.data = data
self.rightval = None
def insert(self, data):
if self.data == None:
self.data = data
else:
if data < self.data:
if self.leftval == None:
self.leftval = node(data)
else:
self.leftval.insert(data)
elif data > self.data:
if self.rightval == None:
self.rightval = node(data)
else:
self.rightval.insert(data)
def printtree(self):
if self.leftval:
self.leftval.printtree()
print (self.data)
if self.rightval:
self.rightval.printtree()
root = int(input("Enter the root value"))
root = node(root)
for i in range (0, 10):
num = int(input("Enter a number"))
root.insert(num)
root.printtree()
该函数基于in-order二叉树遍历。您可以在此处阅读有关树遍历方法的更多信息:Tree_traversal In-order, LNR
我试图弄清楚如何在 python 中制作二叉树,并在网上找到了这段代码。任何人都可以解释 printtree
函数如何能够打印出所有值
class node:
def __init__(self, data):
self.leftval = None
self.data = data
self.rightval = None
def insert(self, data):
if self.data == None:
self.data = data
else:
if data < self.data:
if self.leftval == None:
self.leftval = node(data)
else:
self.leftval.insert(data)
elif data > self.data:
if self.rightval == None:
self.rightval = node(data)
else:
self.rightval.insert(data)
def printtree(self):
if self.leftval:
self.leftval.printtree()
print (self.data)
if self.rightval:
self.rightval.printtree()
root = int(input("Enter the root value"))
root = node(root)
for i in range (0, 10):
num = int(input("Enter a number"))
root.insert(num)
root.printtree()
该函数基于in-order二叉树遍历。您可以在此处阅读有关树遍历方法的更多信息:Tree_traversal In-order, LNR