Python 按顺序打印BST
我正试图按顺序打印出树节点,但所有的结果都是最低深度的NOE!我不确定我的逻辑有什么问题,所以我想知道另一双眼睛是否会帮助我或给我一个提示谢谢 预期产出:Python 按顺序打印BST,python,python-2.7,Python,Python 2.7,我正试图按顺序打印出树节点,但所有的结果都是最低深度的NOE!我不确定我的逻辑有什么问题,所以我想知道另一双眼睛是否会帮助我或给我一个提示谢谢 预期产出: 1 2 3 4 6 8 10 我的代码: class Node: def __init__(self,value): self.right = None self.left = None self.value = value def BST_Insert(root, node):
1
2
3
4
6
8
10
我的代码:
class Node:
def __init__(self,value):
self.right = None
self.left = None
self.value = value
def BST_Insert(root, node): # root --> root of tree or subtree!
if root.value is None:
root = node # beginning of tree
else:
if root.value > node.value: # go to left
if root.left is None:
root.left = node
else:
BST_Insert(root.left, node)
if root.value < node.value: # go to right
if root.right is None:
root.right = node
else:
BST_Insert(root.right, node)
def inorder_print(root):
if root.left is not None:
inorder_print(root.left)
else:
print root.value
if root.right is not None:
inorder_print(root.right)
r = Node(4)
# left
a = Node(2)
b = Node(1)
c = Node(3)
# right
d = Node(8)
e = Node(6)
f = Node(10)
BST_Insert(r, a)
BST_Insert(r, b)
BST_Insert(r, c)
BST_Insert(r, d)
BST_Insert(r, e)
BST_Insert(r, f)
print "in order:"
inorder_print(r)
类节点:
定义初始值(自身,值):
self.right=无
self.left=无
自我价值=价值
def BST_Insert(根,节点):#根-->树或子树的根!
如果root.value为无:
根=节点#树的开头
其他:
如果root.value>node.value:#向左
如果root.left为无:
root.left=节点
其他:
BST_插入(root.left,节点)
如果root.value
我认为您不需要在第一个if
语句之后添加else
。
像下面这样的方法可能会奏效
if left!=null:
inorder(left)
print(current_node.val)
if (right!=null):
inorder(right)