如何在二叉搜索树中遍历一个级别?

时间:2017-02-22 01:29:50

标签: python tree binary-search-tree

我有一个程序,我以递归方式遍历二叉搜索树。但是,一旦我到达某个特定节点,我想转到它的父节点并在两者之间插入一个节点。那么我将如何访问父节点?

谢谢。

编辑: 我使用数组创建了一个树,例如:

tree = ['D', 'Does it have 4 legs?', 
       ['D', 'Can you ride it?', ['I','horse'], ['I', 'dog']], 
       ['D', 'Does it have hands?', ['I', 'monkey'],['I', 'bird']]]

我遍历树的代码:

def identify_thing(tree):
  node_type = tree[0]
  if node_type == "D":
    (question, yes_tree, no_tree) = tree[1:]
    yes_answer = get_yes_no(question)
    if yes_answer:
      identify_thing(yes_tree)
    else:
      identify_thing(no_tree)
  elif node_type == "I":
    name = tree[1]
    question = "Is it a {}?".format(name)
    yes_answer = get_yes_no(question)
    if yes_answer:
      print("{} Identified!".format(name))
    else:
      print("I don't know what it is.")
      new_name = get_nonblank_str("What is it?")
      new_question = get_nonblank_str("Give me a question where yes means 
                   a '{}'" " and no means a '{}'".format(new_name, name))
    # this is where I am trying to insert the code for updating the tree

1 个答案:

答案 0 :(得分:1)

这实际上取决于你如何设计你的树。如果孩子知道他们的父母,那么就像node = node.parent一样简单。如果节点排列在一个数组中(如minheap),则父节点的索引可以计算为node = (n - 1) // 2