In order BST traversal: find

99封情书 提交于 2020-01-25 00:09:05

问题


I am trying to find the kth smallest element of binary search tree and I have problems using recursion. I understand how to print the tree inorder/postorder etc. but I fail to return the rank of the element. Can someone point where I am making a mistake? In general, I am having hard time understanding recursion in trees.

Edit: this is an exercise, so I am not looking for using built-in functions. I have another solution where I keep track of number of left and right children as I insert nodes and that code is working fine. I am wondering if it is possible to do this using inorder traversal because it seems to be a simpler solution.

class BinaryTreeNode:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right


def traverseInOrder(root,order):

    if root == None:

        return
    traverseInOrder(root.left,order+1)
    print root.data,
    print order

    traverseInOrder(root.right,order)


"""
             a
           /   \
          b     c
        /  \   /  \
       d    e f    g
     /  \
    h    i
"""
h = BinaryTreeNode("h")
i = BinaryTreeNode("i")
d = BinaryTreeNode("d", h, i)
e = BinaryTreeNode("e")
f = BinaryTreeNode("f")
g = BinaryTreeNode("g")
b = BinaryTreeNode("b", d, e)
c = BinaryTreeNode("c", f, g)
a = BinaryTreeNode("a", b, c)

print traverseInOrder(a,0)

回答1:


If this is an academic exercise, make traverseInOrder (or similar method tailored to the purpose) return the number of children it visited. From there things get simpler.

If this isn't academic, have a look at http://stromberg.dnsalias.org/~dstromberg/datastructures/ - the dictionary-like objects are all trees, and support iterators - so finding the nth is a matter of zip(tree, range(n)).




回答2:


You could find the smallets element in the binary search tree first. Then from that element call a method to give you the next element k times.

For find_smallest_node method, note that you can traverse all the nodes "in-order" until reach to smallest. But that approach takes O(n) time.

However, you do not need a recursion to find the smallest node, because in BST smallest node is simply the left most node, so you can traverse the nodes until finding a node that has no left child and it takes O(log n) time:

class BST(object):

  def find_smallest_node(self):
    if self.root == None:
      return
    walking_node = self.root
    smallest_node = self.root
    while walking_node != None:
      if walking_node.data <= smallest_node.data:
        smallest_node = walking_node
      if walking_node.left != None:
        walking_node = walking_node.left
      elif walking_node.left == None:
        walking_node = None
    return smallest_node


  def find_k_smallest(self, k):
    k_smallest_node = self.find_smallest_node()
    if k_smallest_node == None:
      return 
    else:
      k_smallest_data = k_smallest_node.data
    count = 1
    while count < k:
      k_smallest_data = self.get_next(k_smallest_data)
      count += 1
    return k_smallest_data


  def get_next (self, key):
   ... 

It just requires to keep the parent of the nodes when inserting them to the tree.

class Node(object):
  def __init__(self, data, left=None, right=None, parent=None):
    self.data = data
    self.right = right
    self.left = left
    self.parent = parent

An implementation of the bst class with the above methods and also def get_next (self, key) function is here. The upper folder contains the test cases for it and it worked.



来源:https://stackoverflow.com/questions/21359873/in-order-bst-traversal-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!