0

我正在尝试按顺序打印树节点,但是它出来的只是深度最低的节点!我不确定我的逻辑有什么问题,所以我想知道另一双眼睛是否会帮助我或给我提示谢谢!

预期输出:

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)
4

1 回答 1

2

我认为您不需要else在第一个if语句之后。像下面这样的东西可能会起作用,

if left!=null: 
    inorder(left)
print(current_node.val)
if (right!=null):
    inorder(right)
于 2013-10-04T09:10:07.290 回答