[英]How to create a Binary Tree in Python?
# Binary tree node
class node:
def __init__(self, data):
self.left=None
self.right=None
self.data=data
# Function to create a new
# Binary node
def newNode(data):
return node(data)
def t():
root=newNode("A")
root.left = newNode("B")
root.right = newNode("C")
root.left.left = newNode("D")
root.left.right = newNode("G")
root.right.right = newNode("E")
root.right.right.left = newNode("F")
print(t)
函数t
只是创建一个二叉树。 如果你想打印一棵树,你需要遍历它并打印它。 根据要打印树的方式,也有不同的穿越技术,它的流行是Inorder
, Preorder
和Postorder
。 检查此wiki 链接以了解树遍历方法。
您的代码必须进行扩展才能进行所需的树遍历。 示例如下:
# Binary tree node
class node:
def __init__(self, data):
self.left=None
self.right=None
self.data=data
# Function to create a new
# Binary node
def newNode(data):
return node(data)
def t():
root=newNode("A")
root.left = newNode("B")
root.right = newNode("C")
root.left.left = newNode("D")
root.left.right = newNode("G")
root.right.right = newNode("E")
root.right.right.left = newNode("F")
return root
def in_order(root):
if root:
in_order(root.left)
print (root.data)
in_order(root.right)
def pre_order(root):
if root:
print (root.data)
pre_order(root.left)
pre_order(root.right)
def post_order(root):
if root:
post_order(root.left)
post_order(root.right)
print (root.data)
root = t()
print ("In Order")
in_order(root)
print ("Pre Order")
pre_order(root)
print ("Post Order")
post_order(root)
输出:
In Order
D
B
G
A
C
F
E
Pre Order
A
B
D
G
C
E
F
Post Order
D
G
B
F
E
C
A
所以两件事:
当您使用print(t)
而不是print(t())
,会有区别。 print(t)
打印函数对象本身,而print(t())
打印函数返回的结果。
但是,即使您执行后者,您也会打印None
因为t()
不返回任何内容。 您需要从t()
返回root
并且您还必须编写一个特殊的函数来遍历树以打印每个节点的值(如果这是您想要的)
下面是一个例子:
# Binary tree node
class node:
def __init__(self, data):
self.left=None
self.right=None
self.data=data
# Function to create a new
# Binary node
def newNode(data):
return node(data)
def t():
root=newNode("A")
root.left = newNode("B")
root.right = newNode("C")
root.left.left = newNode("D")
root.left.right = newNode("G")
root.right.right = newNode("E")
root.right.right.left = newNode("F")
return root
def treeToString(root, level=0):
ret = "\t"*level+repr(root.data)+"\n"
if root.left != None:
ret += treeToString(root.left, level+1)
if root.right != None:
ret += treeToString(root.right, level+1)
return ret
print(treeToString(t()))
# if you want to assign the tree to an object then do this:
tree = t()
print(tree.left.data)
print(tree.right.data)
# Binary tree node
class node:
def __init__(self, data):
self.left=None
self.right=None
self.data=data
# Function to create a new
# Binary node
def newNode(data):
return node(data)
def tree():
root=newNode("A")
root.left = newNode("B")
root.right = newNode("C")
root.left.left = newNode("D")
root.left.right = newNode("G")
root.right.right = newNode("E")
root.right.right.left = newNode("F")
return root
t = tree()
print(t.left.data)
print(t.right.data)
print(t.root)
我如何从这里访问树的根?
我试过打印 t.root 但它似乎有一个错误:(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.