我正在尝试按顺序打印树节点,但它出来的所有内容都是最低深度的noes!我不确定我的逻辑有什么问题,所以我想知道另一组眼睛是否会帮助我或给我一个暗示谢谢!!
预期产出:
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)
答案 0 :(得分:2)
我认为在第一个else
声明之后你不需要if
。
以下内容可能会起作用,
if left!=null:
inorder(left)
print(current_node.val)
if (right!=null):
inorder(right)