Friday, 15 August 2014

Find next greater element in AVL tree -


Let's say I'm following the AVL tree and my job is to get the element of the next element (i.e. 7 for 6) What algorithm can I use?

AVL tree

Again you walk through the nodes and if you are found node 6, then you can return the deep left children ..

< P> pseudo code:

  function find_bigger_key (key, node): If node = null then tap and return if node.key = key then min_node (node) and if the key is & lt; Node.key again find_bigger_key (key, node.left) return_bigger_key (key, node.right) function min_node (node): if node.ltree = null then return the node back and return min_node (node.ltree)  

This is just an example of how you can do it, but it depends on what your AVLTE object model looks like.

An example implementation in Python:

  class AVLTree (object): def __init __ (self, key, ltree = none, rtree = none): self. Key = key; Self.ltree = ltree; Self.rtree = rtree; # Some other features here ... # some other methods here ... def find_bigger_key (self, key): if not self: no return elif self.key == key: if self.rtree: return self.rtree Min_node () Other: Return any elif self.key & gt; Key: return self.left.find_bugger_key (key) Other: return self.find_bigger_key (key)  

An example of a dragon output:

  & Gt; & Gt; & Gt; # ATree is an avltree object that is your example & gt; & Gt; & Gt; Key = 6> gt; & Gt; Found_node = aTree.find_bigger_key (key) & gt; & Gt; & Gt; Print (found_node) >> 7 >> & gt; & Gt; Key = 7> gt; & Gt; & Gt; Found_node = aTree.find_bigger_key (key) & gt; & Gt; & Gt; Print (found_node) none  

No comments:

Post a Comment