2013-10-04 50 views
0

我正在尝试打印出树节点,但是所有它出来的都是最低深度的noes!我不确定我的逻辑有什么问题,所以我想知道如果另一组眼睛会帮助我或给我一个提示,谢谢!打印BST IN订单

预期输出:

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) 

回答

2

我不认为你需要的else的第一if语句之后。 类似以下内容可能工作,

if left!=null: 
    inorder(left) 
print(current_node.val) 
if (right!=null): 
    inorder(right) 
+0

thanks!那就是诀窍! – Liondancer